jquery n.fn.init (0) in test production n.fn.init (1)

0

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:

Test.html (works)

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.

    
asked by anonymous 07.08.2017 / 15:36

2 answers

1

When you connect the element to the blur event, using the blur() method, it searches the page at that time for the selectors and attaches the handler function directly. If you then insert the new form fields, the handler will not be called because it is not attached to the new element.

To work around this, use the on method to delegate events, in the following format:

$(document).on('blur', 'input.placaCss', function() {...});

In this way, the event is not called directly in the element with class placacss , but in the descendants of document that are input and have the class placaCss , which is what the selector in this case says .

This way of attaching events is called delegated events.

Another thing, when using $('.placaCss').blur('input', function() {...}) , you are passing the string input as given, not a selector, as you can see in the documentation for the blur method below.

Sources:

07.08.2017 / 19:17
2

Really as a friend said in the other answer, it's best to use .delegate() . Just change your original code:

From:

$('.placaCss').blur('input', function() {

To:

$(document).delegate('.placaCss','blur', function() {
    
07.08.2017 / 18:27