I have to search inside a json file with a value from my input, everything is fine capturing the value and the event, but when I iterate something unexpected happens for me.
How can I select an object based on this search?.
the problem is that when doing .each it goes through all the records, even those not found.
$( document ).on('turbolinks:load', common_events)
function common_events(){
$('.rut-input').on('change', function(event){
$rut = $(this).val();
var searchField = $rut;
var expression = new RegExp(searchField, "i");
event.preventDefault();
$.ajax({
type: "GET",
url: '/companies/',
dataType: 'JSON',
success: function(companies){
$.each(companies, function(i, company) {
if (company.rut.search(expression) > -1){
console.log(company.id);
$('.name-input').empty();
$('.name-input').val(company.name);
$('.name-input').addClass('disabled-input');
$('.form-group').removeClass('hide');
console.log(company.address);
if (company.address == null ){
$('.address-input').removeClass('disabled-input');
};
}
else {
console.log('no encuentra');
console.log(company);
$('.form-group').removeClass('hide');
$('.form-control').removeClass('disabled-input');
};
});
},
error: function(companies){
console.log('A ocurrido un error')
},
});
});
}
when executing the event, both the if and else are executed at the same time.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…