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

Asked

Viewed 599 times

0

I have a form that creates the input fields dynamically (ASP.NET MVC C#), when the user type in a field, I want to execute an ajax to fill the other fields.

When I created a test.html, with the fixed fields and not being created dynamically, everything works!

As seen in: https://fiddle.jshell.net/nmcpjpss/3/ basically 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 the _this returns n.fn.init(1) which I believe means he found the field. so it works.

But when I run in my dynamically created form, it returns to me n.fn.init(0), I believe that at this point jquery did not find my object in the DOM tree. Because in the test it rises the object pro DOM and in the dynamical form no?

Is there any way I can do what I want?

I also tested with other formats, but all return 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 in dynamic inputs

I found a similar question and it confirms that the error is because the selector was not found in the DOM https://stackoverflow.com/questions/34494873/why-is-my-jquery-selector-returning-a-n-fn-init0-and-what-is-it but does not explain a possible solution.


Update: As suggested I reloaded the Blur, but same error, to make clearer the error in the dynamic form, follow the images:

Test.html (works) inserir a descrição da imagem aqui

Dynamic form (wrong) inserir a descrição da imagem aqui

Final answer

After help from the posts below, I had to make a hybrid solution between Jquery and pure Javascript. It was not the most elegant, but unfortunately it was the only one that worked, using jquery with . nextall did not work in any way.

    $(document).ready(function () {
        $(document).on('blur', 'input.placaCss', function () {
            var valor = $(this).val();
            var _this = $(this);
            // Verificando se o valor foi preenchido
            if (valor) {
                var campo= 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 the css for document.getElementsByClassName that returns me an array and so work with the desired field.

  • Shows code when creating inputs dynamically, probably the error is there.

  • didn’t get it? , I copied the generated html for my test and it worked, the html is in the Fiddler link

  • would who put -1 could guide me why this question is not part of the site scope? since the American question has up.

  • Calm fellow rs, the line var proModelo = _this.nextAll('input.marcaModeloCss:first'); had to return the next input of those, in the fiddle there worked, is that in your HTML they are not brothers? About the document.getElementsByClassName, using as it is you are always changing the first 3 of the document, not necessarily those with respect to the input you took the value.

2 answers

2

Really as a friend spoke in the other answer, it is better to use the .delegate(). Just change your original code:

Of:

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

To:

$(document).delegate('.placaCss','blur', function() {
  • Thanks David, but it didn’t work, see the new images I posted with your code.

  • Missed to call the function aplica() after the return of Ajax.

  • Leave your code as it was and apply the above change in just 1 line of code.

  • Just one observation, delegate() is "deprecated", it is recommended to use the on() according to the documentation: https://api.jquery.com/delegate/

1


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

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

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

Thus, the event is not called directly in the class element placacss, but in the descendants of document who 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.

Something else, when using $('.placaCss').blur('input', function() {...}), you are passing the string input as given, not a selector, as you can see in the method documentation blur further down.

Sources:

  • $('.placaCss'). on('Blur', 'input', Function() { , nor does it perform the function...

  • Now I could look at your HTML and understand how the structure is, I’ve made the adjustment, as David also indicated.

  • now ran, but I’m still with the error that is my announced var proModelo = _this.nextAll('input.marcaModeloCss:first'); does not find the field, it gets the same value of _this

  • They are not of the same value. The string n.fn.init(1) indicates that there is an element in the jQuery object that returned, if you print it on the console, you will see that each of them is a different object.

  • is but in case it is n.fn.init(0) or is it not! _this.nextAll('input.marcaModel:first'); it does not find when it is dynamic

  • Strange... did you see that I attached the event in Document, did it too? I created a Fork of your jsfiddle and it worked correctly for the dynamically added ones: https://fiddle.jshell.net/ya2ng9of/5/

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.