最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Differentiate between two submit buttons in a form using javascript - Stack Overflow

programmeradmin1浏览0评论

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>

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>
Share Improve this question edited Apr 12, 2013 at 16:01 ulentini 2,4121 gold badge15 silver badges25 bronze badges asked Apr 12, 2013 at 15:55 SusieSusie 5,13811 gold badges55 silver badges74 bronze badges 6
  • Not sure about it, but did you try to add name attribute to the input tag? – piokuc Commented Apr 12, 2013 at 15:58
  • 1 Why you don't split it in two forms ? – Marcos Commented Apr 12, 2013 at 15:58
  • @piokuc I did but how do you access the name attribute value in javascript? – Susie 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). – Malkus 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 – piokuc Commented Apr 12, 2013 at 16:06
 |  Show 1 more comment

4 Answers 4

Reset to default 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.

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.

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/

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

发布评论

评论列表(0)

  1. 暂无评论