Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve this simple jQuery issue?

I'm new to jQuery and JavaScript in general. I noticed that if you insert an element via jQuery into the DOM and try to perform an action on that element later, it fails. For example:

I am adding a class of "listenToField" 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')

     });

});

It does not alert 'Hi There'.

However if I hardcode the class "listenToField" into the HTML inputs, the alert works. How can I still have it work when jQuery inserts the class dynamically without resorting to hard coding?

like image 935
George Avatar asked May 12 '11 01:05

George


People also ask

What problems jQuery solve?

jQuery's syntax is designed to make it easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax applications. jQuery also provides capabilities for developers to create plug-ins on top of the JavaScript library.

What is $() in jQuery library?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.

What is jQuery and why is it used?

jQuery is a JavaScript library designed to simplify HTML DOM tree traversal and manipulation, as well as event handling, CSS animation, and Ajax. It is free, open-source software using the permissive MIT License. As of Aug 2022, jQuery is used by 77% of the 10 million most popular websites.


1 Answers

Try jQuery's live method.

The live() method assigns events to elements that exist, and ones that will be created.

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

$('.listenToField').live('keydown', function() {
   alert('Hi there!');
})
like image 127
Felipe Buccioni Avatar answered Oct 17 '22 14:10

Felipe Buccioni