6

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>
6
  • Not sure about it, but did you try to add name attribute to the input tag? Commented Apr 12, 2013 at 15:58
  • 1
    Why you don't split it in two forms ? Commented Apr 12, 2013 at 15:58
  • @piokuc I did but how do you access the name attribute value in javascript? Commented Apr 12, 2013 at 16:01
  • 3
    You should look into using event listeners to pick up your click events instead of binding your function calls inline (which is deprecated). Commented Apr 12, 2013 at 16:03
  • you can access the form, input tags and their attributes via DOM, I just did a google search "how do you access the name attribute value in javascript@ and there was a few pages discussing it Commented Apr 12, 2013 at 16:06

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I initially had one of them as a button. This form has a lot of input fields and my problem is I need to submit the values in these input fields to the server, when I click the button
According to W3Schools only input tags with a name attribute will have their values submitted to the server.
@Kninnug W3Schools is junk, but correct in this case. However, that the form control's value is not submitted does not mean that the form is not submitted. IOW, the form is submitted anyway.
When you click a button instead of a "submit", the input values do not get submitted. How can I make it submit all the inputs in the form, even if you click this "button"?
@PointedEars fair point, but Susie, what exactly do you want now? Must the form be submitted in both the Add and the Find case?
|
4

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.

Comments

3

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/

9 Comments

Wrong: −1. Explicit event listeners are not required (they are implicit with event-handler attributes), and attachEvent is not equivalent to addEventListener.
Yes but inline html event handlers are considered bad practice.
Also, I am aware attachEvent and addEventListener are not the same: hence the conditional statement. IE8 and below need attachEvent.
No, they are not “considered bad practice”; you have been listening to the wrong people. And you are not aware of the differences. IE8 and below do not need attachEvent, they can work like any other DOM 0 browser (down to Netscape 3.0). Avoid attachEvent unless there is an MSHTML-specific reason to use it.
"In Internet Explorer versions prior to IE 9, you have to use attachEvent rather than the standard addEventListener."
|
2

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).

2 Comments

Adding properties to window is worse enough, but really, window.onsubmit? The submit event does not bubble everywhere.
What do you mean it does not bubble everywhere? This solution works across multiple browsers, and window.onsubmit is totally valid in this context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.