Skip to content Skip to sidebar Skip to footer

Two Submit Buttons In One Form. Can Event In Submit Function Know Which One?

I was wonder if in JQuery, this is possible:
&

Solution 1:

You can turn "type='submit'" to "type='button'" so it does not submit form and listen to the buttons clicks:

$("#testform button[type=button]").click(function (e) {
    var submitUrl;
    switch ($(e.target).attr('id')) {
        case'submit1':
            submitUrl = 'url1.cshtml';
            break;
        case'submit2':
            submitUrl = 'url2.cshtml';
            break;
    }

    $.ajax({
                //...
    })
});

Solution 2:

You can maintain the form, just add additional events to setup which button called the submit.

var form_config = {button: null};

$("#submit1").click(function(){
  form_config.button = 'submit1';  
});

$("#submit2").click(function(){
  form_config.button = 'submit2';  
});

$('#testform').submit(function(e) {
    console.log(e);
    e.preventDefault();

    var submiturl;

    if (form_config.button === 'submit1') { submiturl = '../sendToFactory.cshtml'; }
    elseif (form_config.button  === 'submit2') { submiturl = '../sendOverseas.cshtml'; }
    $("#hi").val(submiturl);

});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><formid="testform"><inputtype="text"id="hi"name="hi" /><inputtype="text"id="bye"name="bye" /><buttontype="submit"id="submit1">Use Me</button><buttontype="submit"id="submit2">No, Use Me </button></form>

Solution 3:

If you don't use the submit event of the form and you need to use the button event trigger then you should do something like this :

$('button').click(function(e){
var id$ = $(this).attr('id');
e.preventdefault();

var submiturl;

if (id$ == 'submit1') { submiturl = '../sendToFactory.cshtml'; }
elseif (id$ == 'submit2') { submiturl = '../sendOverseas.cshtml'; }

$.ajax({
    url: submiturl,
    data: $('testform').serialize(),
    type: 'POST',
    datatype: 'json',
    success: function (response) {
        //stuff
    },
    error: function (response) {
        //error
    }
    });
});

Solution 4:

try this

$(document).ready(function() {
    $( "form" ).submit(function () {
        // Get the submit button elementvar btn = $(this).find("button:focus").val();
        alert(btn);
        //DO YOUR AJAX
    });
});

Solution 5:

You can extract the info from new FormData(form) while handling the submit event where form is a reference to <form> element. Note that you have to extract the info while handling the event because even if you go through event loop (e.g. setTimeout(..., 0)) the submit button info has already been lost.

It turns out that latest browsers do not populate FormData with the submit button anymore. So nowadays you can do something like given reference to <form> as form:

form.addEventListener('submit', function(event)
{
    event.preventDefault();
    var formdata = new FormData(form);
    formdata.append(event.submitter.name, event.submitter.value);
    ...
    xhr.send(formdata);
}

The event.submitter will contain a reference to the form button that submitted the form.

In case the form may have multiple submit event handlers and one or more of those may actually modify the data on the form before submitting it (e.g. TinyMCE) you may need to do tricks like

form.addEventListener('submit', function(event)
{
    event.preventDefault();
    let form = this;
    let formdata = newFormData(form);
    let submitter = event.submitter;
    setTimeout(function()
    {
        let formdata = newFormData(form);
        formdata.append(submitter.name, submitter.value);
        xhr.send(formdata);
    }, 0);
}

The setTimeout(..., 0) will allow all existing submit handlers to run and the full event loop to drain empty before proceeding to collect the FormData and send the XHR.

Post a Comment for "Two Submit Buttons In One Form. Can Event In Submit Function Know Which One?"