Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 922
Shaun Avatar asked Nov 27 '25 21:11

Shaun


1 Answers

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.

like image 147
Peter Avatar answered Nov 29 '25 14:11

Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!