简体   繁体   English

在提交动态生成的表单时,找到单击了哪个提交按钮

[英]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. 我有多种形式,这些形式是由模板引擎在运行时动态生成的,为了在提交时生成ajax请求,我使用了“ on”方法来委托事件。

$("#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 2 submit buttons, and i need to detect which of them was clicked and pass this information to the ajax request. 该表单有2个提交按钮,我需要检测单击了哪个按钮,并将此信息传递给ajax请求。 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? 有想法吗?

I hope it will help you : 希望对您有帮助:

$("#friendRequestsList").on("submit", "[id^=friendReqResponse-form]", function(){
     var submit1 = $(this).attr('value');

     var formData = new FormData();
     formData.append('submit1', submit1);

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

    });
    return false;
});

following Connors suggestion of using the click event instead of submit, i have managed to get the the submit button like so: 在康纳斯建议使用click事件而不是Submit的建议之后,我设法获得了Submit按钮,如下所示:

 $("#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. 当然,如果我的表单具有输入字段,这将无法很好地工作,因为它不会在通过Enter键提交表单时被触发。 Also, you still need to append the input identifiying info to the ajax request. 另外,您仍然需要将输入标识信息附加到ajax请求中。

I did this by adding 我通过添加

 data: {submit:input.value},

to the ajaxSubmit settings 到ajaxSubmit设置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM