Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiate between two submit buttons in a form using javascript

How can I find out which submit button was clicked in javascript?

function submitForm(){
   //if find open popup
   //else if add continue in the same window

}

<form action="/findNames" onsubmit="return submitForm()">
    <input type="submit" value="Add" onclick="submitForm(this)"/>
    <input type="submit" value="Find" onclick="submitForm(this)"/>
</form>

WHAT I HAVE TRIED:

I tried to do it with onclick instead as follows but when the "Find" button is clicked it opens a popup window and submits the parent window as well. How can I stop it from submitting the parent window?

function submitForm(submit){
    if(submit.value=="Find"){
        find();//opens a popup window
    }else if(submit.value == "Add"){
        //stay in the same window
    } 
}

function find(){
    var width  = 1010;
    var height = 400;           
    var params = 'width='+width+', height='+height;     
    popupWin = window.open('find.do','windowname5', params);
    popupWin.focus();
}

<form action="/findNames">
    <input type="submit" value="Add" onclick="submitForm(this)"/>
    <input type="submit" value="Find" onclick="submitForm(this)"/>
</form>
like image 896
Susie Avatar asked Apr 12 '13 15:04

Susie


People also ask

Can there be two submit buttons in a form?

yes, multiple submit buttons can include in the html form. One simple example is given below.

How do I tell the difference between two submit buttons in HTML?

Put a hidden field. And when one of the buttons are clicked before submitting, populate the value of hidden field with like say 1 when first button clicked and 2 if second one is clicked. and in submit page check for the value of this hidden field to determine which one is clicked. Save this answer.

What is the difference between submit button and normal button in a form?

It depends on your purpose. In your code, if you want to submit the form to your server, you should use "Submit". However, if you want to do something from client side by clicking the "Button", the input type "Button" is the choice.

How can I use multiple submit buttons in an HTML form?

Let's learn the steps of performing multiple actions with multiple buttons in a single HTML form: Create a form with method 'post' and set the value of the action attribute to a default URL where you want to send the form data. Create the input fields inside the as per your concern. Create a button with type submit.


1 Answers

An input of type="submit" will always submit the form. Use an input of type="button" instead to create a button that doesn't submit.

like image 106
Kninnug Avatar answered Sep 20 '22 06:09

Kninnug