jQuery(或者只是JS)从onSubmit函数中的多个表单提交按钮中进行选择

jQuery (or just JS) choosing from multiple form submit buttons in onSubmit function

本文关键字:表单提交 按钮 选择 行选 函数 或者 JS onSubmit jQuery      更新时间:2023-09-26

我有一个表单,它有多个提交按钮。一个用于更改数据库中的数据,一个用于添加,另一个用于删除。它看起来像这样:

<form action="addform.php" method="post" id="addform" onSubmit="return validate(this)">
<select name="listings" id="listings" size="1" onChange="javascript:updateForm()">
<!-- Here I have a php code that produces the listing menu based on a database query-->
</select>
<br />
Price: <input type="text" name="price" id="price" value="0"/><br />
Remarks:    <textarea name="remarks" wrap="soft" id="remarks"></textarea><br />
<input type="submit" value="Update Database Listing" name="upbtn" id="upbtn" disabled="disabled"/>
<input type="submit" value="Delete Database Listing" name="delbtn" id="delbtn" disabled="disabled"/>
<br />
<input type="submit" value="Add Listing to Database" name="dbbtn" id="dbbtn"/>
<input type="button" value="Update Craigslist Output" name="clbtn" id="clbtn" onClick="javascript:updatePreview();"/>
</form>

实际上,表单中有更多的元素,但这并不重要。我想知道的是,对于我的验证方法,我如何检查点击了哪个提交按钮?

我想让它做以下事情:

    function validate(form){
      if (the 'add new listing' or 'update listing' button was clicked'){
        var valid = "Are you sure the following information is correct?" + '''n';
        valid += "''nPrice: $";
        valid += form.price.value;
        valid += "''nRemarks: ";
        valid += form.remarks.value;
        return confirm(valid);}
      else {
                    return confirm("are you sure you want to delete that listing");
      }
    }

我想一定有什么方法可以相对容易地做到这一点?

为什么不设置一个全局变量来指定上次单击的按钮?然后,您可以在验证方法中检查此变量。类似于:

var clicked;
$("#upbtn").click(function() {clicked = 'update'});
// $("#delbtn").click(function() {clicked = 'delete'});
// ... 
function validate(form) {
    switch(clicked) {
    case 'update':
        break;
            // more cases here ...
    }
}

例如,您可以将一个点击事件附加到每个提交按钮,该按钮将在变量中保存指向它的指针,或者用特定的属性/类标记它(在这种情况下,您必须从事件处理程序中的所有其他提交按钮中删除该标记),然后在提交回调中,您将知道哪个按钮被点击了

我认为在每个按钮上使用一个点击事件并单独处理它更容易。

$(function() {
    $('input[name=someName]').click(someFunc);
});
function someFunc() {
    // Your validation code here
    // return false if you want to stop the form submission
}

您可以在表单上有一个隐藏字段,单击按钮设置该字段的值,然后在验证例程中拾取该字段。您可以使用jquery来实现这一点,如果您需要一个示例,请告诉我。

您可以将ajax提交与jQuery一起使用,您可以尝试以下操作:

$('form#addform input[type="submit"]').on('click',function(e){
        e.preventDefault();
        var current = $(this); //You got here the current clicked button
        var form = current.parents('form');
        $.ajax({
            url:form.attr('action'),
            type:form.attr('method'),
            data:form.serialize(),
            success:function(resp){
                //Do crazy stuff here
            }
        });
});