How to solve this simple jQuery problem?

I am new to jQuery and JavaScript in general. I noticed that if you insert an element through jQuery in the DOM and try to perform an action on this element later, it fails. For instance:

I add the "listenToField" class to all the input elements on the page:

$(function() { $('input').addClass('listenToField'); }); 

Then when I add the second function:

 $(function() { $('input').addClass('listenToField'); // second function $('.listenToField').keydown(function() { alert('Hi There') }); }); 

He does not warn "Hello there."

However, if I rigidly set the listenToField class to HTML inputs, a warning is generated. How can I still work when jQuery dynamically inserts a class without resorting to hard coding?

+6
source share
4 answers

Try the jQuery live method.

The live() method assigns events to existing elements and those that will be created.

http://api.jquery.com/live/

 $('.listenToField').live('keydown', function() { alert('Hi there!'); }) 
+3
source

@ jesus.tesh provides the correct workaround, but the reason for this does not work, as you expect, can be found here .

JQuery only works with elements that exist on load. You need to do further manipulations, as described in the FAQ, if you need it to work with the elements you created.

+3
source

Just cut out the middleman:

 (function() { $('input').keydown(function() { alert('Hi There') }); }); 

You apply the class to all inputs anyway, so just attach the keydown event. You can also apply a class if you need it to style CSS.

+1
source

Another thought, why take two steps? jQuery is chained. The return value of the jQuery function is a jQuery object.

 $("input").addClass("listenToField").keydown(function () { alert("Hi There"); }); 

Do not go too overboard with this. When jQuery chains get too long, they become hard to read.

0
source

Source: https://habr.com/ru/post/887881/


All Articles