Search code examples
jqueryselectclone

Cannot select cloned elements in jquery


After cloning a select element and incrementing the "name" attribute, I am unable to select the cloned elements.

For example:

HTML

<select name="1"></select>

<select name="1-1"></select> <!-- cloned element -->
<select name="1-2"></select> <!-- cloned element -->

JS

$('[name^="1"]').change(function() {
    alert(1);
});

When I change the original element, it works fine I get the alert, but when I change one of the cloned elements, nothing happens. There are no errors.

Note: I am using "name" attribute instead of ID because I need to retrieve these cloned element values once the form is submitted

Should this work?? or is it that the cloned elements cant be selected?


Solution

  • Here's the doc link for live()DOC and here's the one for delegate()DOC

    $('[name^=1]').live('change', function(){
      console.log('hi!');
    });
    

    Although it functions differently than a regular event handler (it's actually listening for events on the document, so it "handles" the event on propagation. Delegate is a little more efficient because you give it a context to listen on:

    $('form').delegate('select[name^=1]', 'change', function(){
      console.log('hi there!');
    });