3

I have a form with two submit buttons, one for create, one for edit

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

Here are my onclick functions:

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();
    });
}

Every time i click the Save button, it goes to the CompanyCreate() function instead of the CompanyEdit() function, what am i doing wrong?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Mindless
  • 2,352
  • 3
  • 27
  • 51
  • You need to handle individual button clicks from jQuery rather than form submit – Naveed Butt Jul 27 '16 at 07:58
  • 2
    Because you handling the forms `.submit()` event and the first function calls `CompanyEdit()` and then you use `preventDefault()` and `stopImmediatePropagation()` so the 2nd function never gets called. –  Jul 27 '16 at 08:01
  • @Stephen How do you prevent form submit without preventDefault, because i am using ajax to submit the form – Mindless Jul 27 '16 at 11:02
  • 1
    Use ` –  Jul 27 '16 at 11:39

4 Answers4

4

You can do something as follows:

$('#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');
}
<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>

UPDATE

If you do not wish to use the former example, you can simply do the following. Not that using events like onclick in the dom is considered as bad practice and should be done in 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');
});

Here is working js-fiddle

Subash
  • 7,098
  • 7
  • 44
  • 70
  • Thanks, I don't really like the idea of checking the name attribute of the button and using if statements to decide which function to run, the buttons are already unique, i don't see why we have to check which button was clicked using their names. And also, when you have the names changed, whos going to know that it is binded to some function. I've solved the problem using the click function. – Mindless Jul 28 '16 at 02:46
0
<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>

Jquery code is

      $(document).ready(function () {


        $("#CompanyCreate").click(function () {
            //your code here
        });
        $("#CompanyEdit").click(function () {
            //your code here
        });
    });
Rayudu
  • 40
  • 3
0

Simple pattern I use (MVC based): 1. Create custom attribute

[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. Controller

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

public ActionResult Action1(MyModel model)

{...}

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

public ActionResult Action2(MyModel model)")]

{...}

3. View

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

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

   <button type="submit" name="action:Action2" >Action2</button>
}
Xavr
  • 229
  • 1
  • 13
0

Prevent using .submit function inside .click, it will not work, instead you have to grab the form and post it.

NO

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

        //prevent default submit
        event.preventDefault();

        //ajax post etc...

YES

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

    //ajax post etc..

Remember your button type has to be type="button" instead of the default type="submit"

<button id="companyCreateSubmitBtn" name="add" class="ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25" type="button">Add</button>
Mindless
  • 2,352
  • 3
  • 27
  • 51