简体   繁体   中英

How to select dynamically created elements with jQuery

I'm updating some elements dynamically based on user-input. Specifically, I have a table of form fields which the user can fill in. When the page loads I can count how many are empty...

$(whocares).click(callback);

callback = function() {
    var empties = $('.something input[value=""]);
    var count = empties.length; //4
}

but after the user fills in new ones, the count stays the same.

When I inspect the DOM, I don't see the updated values either. The new form fields still say: value instead of value="whatever" .

All the jQuery is inside $(document).ready();

How do I get jQuery to see the new changes?

As of jQuery 1.9, the [value=] notation in selectors, only deals with attributes (.attr) and these attributes do not match the current state of form elements, but the 'value' attribute of the element.

Only the property (.prop) of the form element will map the current value of this element.

you can get the empty elements via

$(":input").filter(function () { return $(this).val() === ""; });

you can read the jQuery 1.9 upgrade guide for more information.

This code:

var count = 0;
$('.something input').each(function()
    if($(this).val().length = 0) {
        count++;
    }
});

First thing is to know that when you run a jQuery selector you're asking it to look at the current state of the DOM and find the elements that match your selector. When you set a variable to equal the result of that jQuery function, you end up with an array of jQuery elements which represent the DOM elements that were matched. When accessing that cached variable you do not ask the DOM again for matching elements.

So for example:

var empties = $('.something input[value^=""]');
empties.length // 4;

If the DOM then changes state, IE: you put some values in two of the input fields, empties.length remains 4 because it's just a cache of the previous selection - it's not doing the selection again. In order to check to see how many empties there are now, you need to do the selection again $('.something input[value^=""]').length would now equal 2.

So the solution here is not to cache the result of the selection in empties but to just call $('.something input[value^=""]').length directly and it'll give you the number of matches to that selector (the number of empties in this example) straight from the DOM every time it's run.

You could use something like

$(document).on("change", "youtInput.YourImputClass", function(){
  var count = $(document).find("youtInput.YourImputClass[value^='']").length;
}

That should do the trick.

Hope this will be helpfull. Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM