'Issue with triggering the submit function with included js file

I'm have a problem triggering the form submission. I am setting the form into <div id="access"></div> innerHTML using the included js file in the header of page. As:

<div id="access">
    <form method="post" id="acc">
        <input type="text">
        <input type="submit">
    </form>
</div>

The form submission is implementing in the included js file in the header, but they are not listening my submit function, which is implemented as:

$('#acc').submit(function(){
  alert("dsds");
  return false;
});

Same js function also not working in the same file. How can I make it listen the above lead_form submission?



Solution 1:[1]

It's because jQuery's selector only acts on elements that exist on the page at the time it's ran.

Instead, use the jQuery.on() function.

$('#access').on('submit', '#acc', function() { /* Your code here. */ });

Edit For some clarification: '#access' exists at run-time, so therefore you can bind an event to it, which then refers to it's child element '#acc'. Keep in mind that the context of 'this' while in the anonymous function will refer to '#acc' and not '#access', despite using the $('#access') selector.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1