两个提交按钮在同一个表单中

时间:2016-07-27 07:56:30

标签: javascript jquery html forms

我有一个带有两个提交按钮的表单,一个用于创建,一个用于编辑

<div class="modal-footer">
    <button name="add" class="companyCreateSubmitBtn ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25" onclick="CompanyCreate()">Add</button>
    <button name="edit" class="companyEditSubmitBtn ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25" onclick="CompanyEdit()">Save</button>
</div>

以下是我的onclick功能:

function CompanyCreate() {
    //work experience create
    $("#companyForm").submit(function (event) {
        //validate form
        if (!$(this).valid()) {
            return;
        }

        //serialize the form
        serializedForm = $(this).serializeArray();
        cvId = $("#CVId").val();
        serializedForm.push({ name: "cvId", value: cvId });

        //ajax post
        $.ajax({
            url: "@Url.Action("CompanyCreate", "CV")",
            type: "POST",
            data: serializedForm,
            beforeSend: function () {
                l.ladda("start");
            },
            success: function (result) {
                if (result.success) {
                    //add row to table
                    cTable.fnAddData([
                        result.id,
                        result.name,
                        result.title,
                        result.city,
                        result.country,
                        $.datepicker.formatDate("dd/mm/yy", new Date(parseInt(result.startdate.substr(6)))),
                        $.datepicker.formatDate("dd/mm/yy", new Date(parseInt(result.enddate.substr(6)))),
                        result.description,
                        "<button class='companyEditBtn btn'' title='Edit Work Experience'><i class='icon-pencil'></i></button>" + " " + "<button class='companyDeleteBtn btn'><i class='icon-trash'></i></button>"
                    ]);

                    //success
                    toastrSuccess(result.message);
                } else {
                    //fail
                    toastrError(result.message);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //fail
                toastrError(textStatus);
            },
            complete: function () {
                //stop ladda button loading
                l.ladda("stop");
                //hide modal
                $(".modal").modal("hide");
            }
        });

        //prevent default submit behaviour
        event.preventDefault();
        event.stopImmediatePropagation();
    });
}



function CompanyEdit() {
    //work experience edit
    $("#companyForm").submit(function (event) {
        //validate form
        if (!$(this).valid()) {
            return;
        }

        //serialize the form
        serializedForm = $(this).serialize();

        //ajax post
        $.ajax({
            url: "@Url.Action("CompanyEdit", "CV")",
            type: "POST",
            data: serializedForm,
            beforeSend: function () {
                l.ladda("start");
            },
            success: function (result) {
                if (result.success) {
                    //update row of table
                    cTable.fnUpdate([
                        result.id,
                        result.name,
                        result.title,
                        result.city,
                        result.country,
                        $.datepicker.formatDate("dd/mm/yy", new Date(parseInt(result.startdate.substr(6)))),
                        $.datepicker.formatDate("dd/mm/yy", new Date(parseInt(result.enddate.substr(6)))),
                        result.description,
                        "<button class='companyEditBtn btn'' title='Edit Work Experience'><i class='icon-pencil'></i></button>" + " " + "<button class='companyDeleteBtn btn' title='Delete Work Experience'><i class='icon-trash'></i></button>"
                    ], position);

                    toastrSuccess(result.message);
                } else {
                    toastrError(result.message);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastrError(textStatus);
            },
            complete: function () {
                //stop ladda button loading
                l.ladda("stop");
                //hide modal
                $(".modal").modal("hide");
            }
        });

        //prevent default submit behaviour
        event.preventDefault();
        event.stopImmediatePropagation();
    });
}

每次我点击“保存”按钮,它都会转到CompanyCreate()函数而不是CompanyEdit()函数,我做错了什么?

4 个答案:

答案 0 :(得分:4)

您可以执行以下操作:

&#13;
&#13;
$('#companyForm').on('submit', function(e) {
	e.preventDefault(); // stops form from being submitted
  
  // get the clicked button name
  var clickedButton = $(document.activeElement).attr('name');
  
  if (clickedButton === 'edit') {
  	companyEdit();
  }
  
  if (clickedButton === 'add') {
  	companyAdd();
  }
});

function companyEdit() {
    // your code to edit company
	alert('editing company');
}

function companyAdd() {
    // your code to add company
	alert('adding company');
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-footer">
    <form id="companyForm">
      <button name="add" class="companyCreateSubmitBtn ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25">Add</button>
      <button name="edit" class="companyEditSubmitBtn ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25">Save</button>
    </form>
</div>
&#13;
&#13;
&#13;

<强>更新

如果您不想使用前一个示例,则只需执行以下操作即可。并非在dom中使用onclick之类的事件被认为是不好的做法,应该在javascript中完成。

$('.companyEditSubmitBtn').on('click', function(e) {
    e.preventDefault(); // stops form from being submitted

  alert('editing company');
});

$('.companyCreateSubmitBtn').on('click', function(e) {
    e.preventDefault(); // stops form from being submitted

  alert('creating company');
});

这是有效的js-fiddle

答案 1 :(得分:0)

SELECT

Jquery代码是

<div class="modal-footer">
    <button type="button" id="CompanyCreate" name="add" class="companyCreateSubmitBtn ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25">Add</button>
    <button type="button" id="CompanyEdit"  name="edit" class="companyEditSubmitBtn ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25">Save</button>
</div>

答案 2 :(得分:0)

我使用的简单模式(基于MVC):  1.创建自定义属性

[AttributeUsage(AttributeTargets.Method)]
public class MultipleButtonAttribute : ActionNameSelectorAttribute
{
    public string Name { get; set; }
    public string Argument { get; set; }

    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
    {
        var isValidName = false;
        var keyValue = string.Format("{0}:{1}", Name, Argument);
        var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);

        if (value != null)
        {
            controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
            isValidName = true;
        }

        return isValidName;
    }
}

2。控制器

MultipleButton(Name = "action", Argument = "Action1")

public ActionResult Action1(MyModel model)

{...}

[MultipleButton(Name = "action", Argument = "Action2")

public ActionResult Action2(MyModel model)")]

{...}

3。图

@using (Ajax.BeginForm("Action1", "Search", new AjaxOptions { }))
{

   <button type="submit" name="action:Action1" >Action1</button>

   <button type="submit" name="action:Action2" >Action2</button>
}

答案 3 :(得分:0)

防止在.click中使用.submit功能,它不起作用,而是你必须抓住表格并发布。

$("#companyCreateSubmitBtn").click(function () {
    $("#companyForm").submit(function (event) {
        //validate form
        if (!$(this).valid()) {
            return;
        }

        //prevent default submit
        event.preventDefault();

        //ajax post etc...

$("#companyCreateSubmitBtn").click(function () {
    //get the form
    var form = $("#companyForm");
    //validate form
    if (!form.valid()) {
        return;
    }

    //ajax post etc..

请记住,您的按钮类型必须是type =“button”而不是默认类型=“提交”

<button id="companyCreateSubmitBtn" name="add" class="ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25" type="button">Add</button>