我可以确定在 javascript 中使用了哪个提交按钮吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2298635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:40:03  来源:igfitidea点击:

Can I determine which Submit button was used in javascript?

javascript

提问by Scott Saunders

I have a very simple form with a name field and two submit buttons: 'change' and 'delete'. I need to do some form validation in javascript when the form is submitted so I need to know which button was clicked. If the user hits the enter key, the 'change' value is the one that makes it to the server. So really, I just need to know if the 'delete' button was clicked or not.

我有一个非常简单的表单,其中包含一个名称字段和两个提交按钮:“更改”和“删除”。提交表单时,我需要在 javascript 中进行一些表单验证,因此我需要知道单击了哪个按钮。如果用户按下回车键,则“更改”值是将其发送到服务器的值。所以真的,我只需要知道“删除”按钮是否被点击。

Can I determine which button was clicked? Or do I need to change the 'delete' button from a submit to a regular button and catch its onclick event to submit the form?

我可以确定点击了哪个按钮吗?或者我是否需要将“删除”按钮从提交更改为常规按钮并捕获其 onclick 事件以提交表单?

The form looks like this:

表格如下所示:

 <form action="update.php" method="post" onsubmit="return checkForm(this);">
    <input type="text" name="tagName" size="30" value="name goes here" />
    <input type="hidden" name="tagID" value="1" />
    <input type="submit" name="submit" value="Change" />
    <input type="submit" name="submit" value="Delete" />
 </form>

In the checkForm()function, form["submit"]is a node list, not a single element I can grab the value of.

checkForm()函数中,form["submit"]是一个节点列表,而不是我可以获取值的单个元素。

采纳答案by Glen Little

You could also use the onclickevent in a number of different ways to address the problem.

您还可以通过onclick多种不同方式使用该事件来解决问题。

For instance:

例如:

<input type="submit" name="submit" value="Delete" 
       onclick="return TryingToDelete();" />

In the TryingToDelete()function in JavaScript, do what you want, then return falseif do not want the delete to proceed.

TryingToDelete()JavaScript 中的函数中,做你想做的,然后return false如果不想继续删除。

回答by cllpse

Here's an unobtrusive approachusing jQuery...

这是使用 jQuery的一种不显眼的方法......

$(function ()
{
    // for each form on the page...
    $("form").each(function ()
    {
        var that = $(this); // define context and reference

        /* for each of the submit-inputs - in each of the forms on
           the page - assign click and keypress event */
        $("input:submit", that).bind("click keypress", function ()
        {
            // store the id of the submit-input on it's enclosing form
            that.data("callerid", this.id);
        });
    });


    // assign submit-event to all forms on the page
    $("form").submit(function ()
    {
        /* retrieve the id of the input that was clicked, stored on
           it's enclosing form */
        var callerId = $(this).data("callerid");

        // determine appropriate action(s)
        if (callerId == "delete") // do stuff...

        if (callerId == "change") // do stuff...

        /* note: you can return false to prevent the default behavior
           of the form--that is; stop the page from submitting */ 
    });
});

Note:this code is using the id-property to reference elements, so you have to update your markup. If you want me to update the code in my answer to make use of the name-attribute to determine appropriate actions, let me know.

注意:此代码使用 id-property 来引用元素,因此您必须更新标记。如果您希望我更新我的答案中的代码以使用 name-attribute 来确定适当的操作,请告诉我。

回答by ps.

<html>
<script type="text/javascript">
var submit;
function checkForm(form)
{
alert(submit.value);
return false;
}

function Clicked(button)
{
  submit= button ;
}
</script>
<body>
 <form method="post" onsubmit="return checkForm(this);">
    <input type="text" name="tagName" size="30" value="name goes here" />
    <input type="hidden" name="tagID" value="1" />
    <input onclick="Clicked(this);" type="submit" name="submit" value="Change" />
    <input onclick="Clicked(this);" type="submit" name="submit" value="Delete" />
 </form>
 </body>
</html>

回答by Christoph

Some browsers (at least Firefox, Opera and IE) support this:

一些浏览器(至少 Firefox、Opera 和 IE)支持这个:

<script type="text/javascript">
function checkForm(form, event) {
    // Firefox || Opera || IE || unsupported
    var target = event.explicitOriginalTarget || event.relatedTarget ||
        document.activeElement || {};

    alert(target.type + ' ' + target.value);
    return false;
}
</script>
<form action="update.php" method="post" onsubmit="return checkForm(this, event);">
   <input type="text" name="tagName" size="30" value="name goes here" />
   <input type="hidden" name="tagID" value="1" />
   <input type="submit" name="submit" value="Change" />
   <input type="submit" name="submit" value="Delete" />
</form>

For an inherently cross-browser solution, you'll have to add onclickhandlers to the buttons themselves.

对于固有的跨浏览器解决方案,您必须向onclick按钮本身添加处理程序。

回答by Wojciech Dynus

In jQuery you can use $.data() to keep data in scope - no need for global variables in that case. First you click submit button, then (depending on it's action) you assign data to form. I'm not preventing default action in click event, so form is submitted right after click event ends.

在 jQuery 中,您可以使用 $.data() 将数据保留在范围内 - 在这种情况下不需要全局变量。首先单击提交按钮,然后(取决于它的操作)将数据分配给表单。我没有阻止点击事件中的默认操作,因此在点击事件结束后立即提交表单。

HTML:

HTML:

<form action="update.php" method="post"">
    <input type="text" name="tagName" size="30" value="name goes here" />
    <input type="hidden" name="tagID" value="1" />
    <input type="submit" name="submit" value="Change" />
    <input type="submit" name="submit" value="Delete" />
</form>

JavaScript:

JavaScript:

 (function ($) {
        "use strict";
        $(document).ready(function () {

            // click on submit button with action "Change"
            $('input[value="Change"]').on("click", function () {
                var $form = $(this).parents('form');
                $form.data("action", "Change");
            });

            // click on submit button with action "Delete"
            $('input[value="Delete"]').on("click", function () {
                var $form = $(this).parents('form');
                $form.data("action", "Delete");
            });

            // on form submit
            $('form').on("submit", function () {
                var $self = $(this);

                // retrieve action type from form
                // If there is none assigned, go for the default one
                var action = $self.data("action") || "deafult";

                // remove data so next time you won't trigger wrong action
                $self.removeData("action");

                // do sth depending on action type
                if (action === "change") {
                }
            });
        });
    })(jQuery);

回答by Catfish

Give each of the buttons a unique ID such as

给每个按钮一个唯一的 ID,例如

<input type="submit" id="submitButton" name="submit" value="Change" />
<input type="submit" id="deleteButton" name="submit" value="Delete" />

I'm not sure how to do this in raw javascript but in jquery you can then do

我不确定如何在原始 javascript 中执行此操作,但是在 jquery 中您可以执行此操作

$('#submitButton').click(function() {
  //do something
});
$('#deleteButton').click(function() {
  //do something
});

This says that if submitButton is clicked, do whatever is inside it. if deleteButton is clicked, do whatever is inside it

这表示如果单击 submitButton,则执行其中的任何操作。如果单击 deleteButton,则执行其中的任何操作

回答by Michael Stone

Right now you've got the same problem as you would a normal text input. You've got the same name on two different elements. Change the names to "Change" and "Delete" and then determine if either one of them were clicked by applying an event handler on both submits and providing different methods. I'm assuming you're using pure JavaScript, but if you want it to be quick, take a look at jQuery.

现在您遇到了与普通文本输入相同的问题。你在两个不同的元素上有相同的名字。将名称更改为“更改”和“删除”,然后通过在提交时应用事件处理程序并提供不同的方法来确定它们中的任何一个是否被单击。我假设您使用的是纯 JavaScript,但如果您希望它快速,请查看 jQuery。

What you need is as simple as following what's on w3schools

您需要的就像遵循w3schools上的内容一样简单

回答by Patanjali

A clickevent anywhere in a form will be caught by a form's clickhandler (as long as the element clicked on allows it to propagate). It will be processed before the form's submitevent.

click表单中任何位置的事件都将被表单的click处理程序捕获(只要单击的元素允许它传播)。它将在表单submit事件之前处理。

Therefore, one can test whether the click target was an input(or button) tag of the submittype, and save the value of it (say, to a data-buttonattribute on the form) for processing in the form's submithandler.

因此,可以测试点击目标是否是该类型的input(或button)标记submit,并保存它的值(比如,到data-button表单上的一个属性)以便在表单的submit处理程序中进行处理。

The submit buttons themselves do not then need any event handlers.

提交按钮本身不需要任何事件处理程序。

I needed to do this to change a form's actionand targetattributes, depending upon which submit button is clicked.

我需要这样做来更改表单的actiontarget属性,具体取决于单击的提交按钮。

// TO CAPTURE THE BUTTON CLICKED    
function get_button(){
 var oElement=event.target;
 var oForm=oElement.form;
 
 // IF SUBMIT INPUT BUTTON (CHANGE 'INPUT' TO 'BUTTON' IF USING THAT TAG)
 if((oElement.tagName=='INPUT')&&(oElement.type=='submit')){
  // SAVE THE ACTION
  oForm.setAttribute('data-button',oElement.value);
 }
}

// TO DO THE SUBMIT PROCESSING    
function submit_form(){
 var oForm=event.target;

 // RETRIEVE THE BUTTON CLICKED, IF ONE WAS USED     
 var sAction='';
 if(oForm.hasAttribute('data-button')){
  // SAVE THE BUTTON, THEN DELETE THE ATTRIBUTE (SO NOT USED ON ANOTHER SUBMIT)     
  sAction=oForm.getAttribute('data-button');
  oForm.removeAttribute('data-button');
 }

 // PROCESS BY THE BUTTON USED     
 switch(sAction){
  case'Change':
   // WHATEVER
   alert('Change');
   break;
  case'Delete':
   // WHATEVER
   alert('Delete');
   break;
  default:
   // WHATEVER FOR ENTER PRESSED
   alert('submit: By other means');
   break;
 }
} 
 <form action="update.php" method="post" onsubmit="submit_form();" onclick="get_button();">
    <input type="text" name="tagName" size="30" value="name goes here" />
    <input type="hidden" name="tagID" value="1" />
    <input type="submit" name="submit" value="Change" />
    <input type="submit" name="submit" value="Delete" />
 </form>
 <p id="result"></p>

回答by Alex Beardsley

Since you didn't mention using any framework, this is the cleanest way to do it with straight Javascript. With this code what you're doing is passing the button object itself into the go() function. You then have access to all of the button's properties. You don't have to do anything with setTimeout(0) or any other wacky functions.

由于您没有提到使用任何框架,因此这是使用直接 Javascript 最简洁的方法。使用这段代码,您所做的是将按钮对象本身传递给 go() 函数。然后,您可以访问按钮的所有属性。您不必对 setTimeout(0) 或任何其他古怪的函数做任何事情。

<script type="text/javascript">
    function go(button) {
        if (button.id = 'submit1')
            //do something
        else if (button.id = 'submit2')
            //do something else
    }
</script>

<form action="update.php" method="post">
    <input type="text" name="tagName" size="30" value="name goes here" />
    <input type="hidden" name="tagID" value="1" />
    <input id="submit1" type="submit" name="submit" value="Change" onclick="go(this);"/>
    <input id="submit2" type="submit" name="submit" value="Delete" onclick="go(this);"/>
</form>

回答by s4y

I've been dealing with this problem myself. There's no built-in way to tell which button's submitting a form, but it's a feature which might show up in the future.

我自己一直在处理这个问题。没有内置的方法来判断哪个按钮正在提交表单,但它是一个将来可能会出现的功能。

The workaround I use in production is to store the button somewhere for one event loop on click. The JavaScript could look something like this:

我在生产中使用的解决方法是将按钮存储在某处,以便在单击时进行一个事件循环。JavaScript 可能看起来像这样:

function grabSubmitter(input){
    input.form.submitter = input;
    setTimeout(function(){
        input.form.submitter = null;
    }, 0);
}

... and you'd set an onclick on each button:

...你会在每个按钮上设置一个onclick:

<input type="submit" name="name" value="value" onclick="grabSubmitter(this)">

clickfires before submit, so in your submit event, if there's a submitter on your form, a button was clicked.

click触发 before submit,因此在您的提交事件中,如果您的表单上有提交者,则会单击一个按钮。



I'm using jQuery, so I use $.fn.data()instead of expando to store the submitter. I have a tiny plugin to handle temporarily setting data on an element that looks like this:

我正在使用 jQuery,所以我使用$.fn.data()而不是 expando 来存储提交者。我有一个小插件来处理一个元素上的临时设置数据,如下所示:

$.fn.briefData = function(key, value){
        var $el = this;
        $el.data(key, value);
        setTimeout(function(){
            $el.removeData(key);
        }, 0);
    };

and I attach it to buttons like this:

我把它附加到这样的按钮上:

$(':button, :submit').live('click', function () {
    var $form = $(this.form);
    if ($form.length) {
        $form.briefData('submitter', this);
    }
});