Susie
Susie

Reputation: 5138

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>

Upvotes: 6

Views: 9367

Answers (4)

PointedEars
PointedEars

Reputation: 14970

You are on the right track, but your form is submitted always because you are not canceling the events (or, in DOM Level 2+ parlance, you are not “preventing the default action for the event”).

function submitForm (button)
{
  if (button.value == "Find")
  {
    /* open popup */
    find();
  }
  else if (button.value == "Add")
  {
    /* stay in the same window */
  } 

  return false;
}

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

(You should never name a form-related variable submit because if you are not careful that overrides the form object's submit method.)

The return value false, when returned to the event handler, prevents the default action for the click event. This means the user agent works as if the submit button was never activated in the first place, and the form is not submitted.

Another approach to solve this is to save a value identifying the clicked submit button in a variable or property, and check that value in the submit event listener. This works because the click event of the input (submit button) by definition happens before the submit event of the form:

var submitName;

function submitForm (form)
{
  if (submitName == "Find")
  {
    /* open popup */
    find();
  }
  else if (submitName == "Add")
  {
    /* stay in the same window */
  } 

  return false;
}

function setSubmit (button)
{
  submitName = button.value;
}

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

(This is just an example. Try to minimize the number of global variables.)

Again, the return value false, when returned to the submit event handler, prevents the form from being submitted. You may want to return true instead if you explicitly want the form to be submitted after you handled the submit event. For example, you may want to validate the form and if validation was successful, display the server response in another frame, through the target attribute.

The advantage of event-handler attributes over adding event listeners in script code is that it is runtime-efficient, backwards-compatible, and still standards-compliant. The disadvantage is that you may have to duplicate event-handler code if the event does not bubble. (Not an issue here.)

Other people may say that a disadvantage of event-handler attributes is also that there is no separation between markup and function; however, you should make up your own mind about that. In my opinion, function is always tied to specific markup, and the jumping through hoops for working around different DOM implementations is seldom worth it.

See also: DOM Client Object Cross-Reference: DOM Events

The most important thing here is that, regardless of all client-side improvements that you make, the form stays accessible, i. e. that it still works with the keyboard even without client-side scripting. Your server-side script (here: /findNames) can work as fallback, then, and the client-side script can avoid unnecessary roundtrips, improving the user experience and reducing the network and server load.

Upvotes: 4

Hanlet Esca&#241;o
Hanlet Esca&#241;o

Reputation: 17380

Check this out:

Javascript:

var clicked;
var buttons = document.getElementsByTagName("input");

for(var i = 0; i < buttons.length;i++)
{
    var elem = buttons[i];
    if(elem.type=="submit")
    {
        elem.addEventListener("click", function(){ clicked=this.value;}, false);
    }
}


window.onsubmit = function(e)
{
   alert(clicked);
    return false;
}

Markup:

<form action="/findNames">
    <input type="submit" value="Add" />
    <input type="submit" value="Find" />
</form>

You will have the value of whatever button was clicked.

jsFiddle: http://jsfiddle.net/hescano/v9Sz2/

Note: For testing purposes I have the return false inside the onsubmit event. The first jsFiddle sample has its own window.onload included, so you may want to add everything that's not inside the window.onsubmit inside window.onload, like this http://jsfiddle.net/hescano/v9Sz2/1/ (Tested in Chrome, Firefox).

Upvotes: 2

chrx
chrx

Reputation: 3572

Your code should be refactored to properly attach event listeners.

First, define your functions that will serve as listeners:

function preventSubmission(e) {
    if (e.preventDefault) e.preventDefault();
    return false;
}

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

Then, cache references to the relevant form elements:

var form = document.getElementById('my-form'),
    findButton = document.getElementById('find');

And finally, add the listeners to the DOM events:

if (form.addEventListener) {
    form.addEventListener("submit", preventSubmission);
    findButton.addEventListener("click", find);
} else {
    form.attachEvent("submit", preventSubmission);
    findButton.attachEvent("click", find);
}

Here's a full working demo: http://jsfiddle.net/CQAHv/2/

Upvotes: 3

Kninnug
Kninnug

Reputation: 8053

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.

Upvotes: 7

Related Questions