Search code examples
jqueryformsdynamicpreventdefault

How to use preventDefault on dynamic elements?


I have a bunch of forms that get dynamically created and added to a div. The id of each form is also dynamically created - the ids are always different, but they all start with...

updateFRM_

I can't get preventDefault() to work - I'm not sure if that's the problem, or if the syntax is so incorrect that the js is failing and reloading.

What's the correct syntax for setting up listeners for forms that are both dynamically generated and dynamcially named?

$( "#updater" ).on( "submit", "form[id^='updateFRM_']", function(e)
{ 
    e.preventDefault();

Thanks for your time and help


Solution

  • Using the $(document) selector, you can target elements that are dynamically generated. This is because the document covers the dom and not just the html that is loaded initially. Below are two examples on what you can do. It depends entirely on your code and the way you are going to use this which of the two you pick.

    ID based

    var formid = 'someformid';
    $(document).on('submit', '#' + formid, function(e) {
        e.preventDefault();
        // Do your form stuff
        return false;
    });
    

    Class based

    $(document).on('submit', '.my-form', function(e) {
        e.preventDefault();
        var formid = $(this).attr('id');
        // Do stuff with the formid 
        return false;
    });
    

    Update

    The return false; is not required. I added it in case e.preventDefault() fails. Some jQuery versions have different ways of preventing the default action. Using a return false; does the same thing. It executes the code above and then, instead of doing the default action returns false.