Skip to content
Advertisement

on submit of dynamically generated form, find which submit button was clicked

I have multiple forms which are dynamically generated at runtime by a template engine, in order to generate an ajax request on their submission I have used the on method to delegate the event.

$("#friendRequestsList").on("submit", "[id^=friendReqResponse-form]", function(){
    var form = this;
    $(form).ajaxSubmit({
        url:'URL',
        type:'post',
        dataType: 'json',
        success: function(data) {
            DO SOMETHING
        }

    });
    return false;
});

The form has two submit buttons, and I need to detect which of them was clicked and pass this information to the ajax request. However I am having a hard time knowing which of the submit inputs in the form was clicked, as they have also been dynamically generated. Ideas?

Advertisement

Answer

following Connors suggestion of using the click event instead of submit, i have managed to get the the submit button like so:

 $("#friendRequestsList").on("click", "[id^=submit1], [id^=submit2]", function(e) {
    var input = this;
    var form = $(input).parent();

    $(form).ajaxSubmit({
        url:'URL',
        type:'post',
        dataType: 'json',
        success: function(data) {
            DO SOMETHING
        }

    });
    e.preventDefault()
});

of course, this wouldn’t work so well if my form had input fields as it wouldn’t be triggered on a form submission from a keypress Enter. Also, you still need to append the input identifiying info to the ajax request.

I did this by adding

 data: {submit:input.value},

to the ajaxSubmit settings

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement