I have a form that creates the input fields dynamically (ASP.NET MVC C #), when the user types in a field, I want to execute an ajax to populate the other fields.
When I created a test.html, with the fields fixed and not being created dynamically, everything works!
As seen in: link basically it is the following code:
$(document).ready(function() {
$('.placaCss').blur('input', function() {
var valor = $(this).val();
var _this = $(this); //Esta linha retorna n.fn.init(1)
// Verificando se o valor foi preenchido
if (valor) {
var proModelo = _this.nextAll('input.marcaModeloCss:first');
proModelo.val(valor);
}
});
});
When debugging in Chrome, I realize that _this
returns n.fn.init(1)
which I believe means that it found the field. so it works.
But when I run on my dynamically created form, it returns me n.fn.init (0), I believe that at the moment jquery did not find in the DOM tree my object. Because in the test it goes up the DOM object and in the dynamic form does not?
Is there any way I can do what I want?
I also tested other formats, but all returned the wrong field in the dynamic form and correct in the test.
var t1 = _this.nextAll('.marcaModeloCss:first');
var t2 = _this.nextAll('.marcaModeloCss').first();
var t3 = _this.nextUntil().last().next();
My original question: jquery blur on dynamic inputs
I found a similar question and it confirms that the error is because the selector was not found in the DOM link but does not explain a possible solution.
Update: As a suggestion I did the reloading of the blur, but same error, to make clear the error in the dynamic form, it follows the images:
Dynamicform(wrong)
Finalanswer
Afterthehelpofthepostsbelow,IhadtomakeahybridsolutionbetweenJqueryandpureJavascript.Itdidnotlookthemostelegant,butunfortunatelyitwastheonlyonethatworked,usingjquerywith.nextalldidnotworkinanyway.
$(document).ready(function(){$(document).on('blur','input.placaCss',function(){varvalor=$(this).val();var_this=$(this);//Verificandoseovalorfoipreenchidoif(valor){varcampo=document.getElementsByClassName('MarcaModelo');$.ajax({type:"GET",
url: "/ConsultaVeiculo/Placa?placa=" + valor,
dataType: "json",
success: function (data) {
campo[0].value = data.content.bin.marca;
campo[1].value = data.content.bin.ano_fabricacao;
campo[2].value = data.content.bin.ano_modelo;
}
});
}
});
});
In short, I had to search for css by document.getElementsByClassName
that returns an array and thus work with the desired field.