two submit buttons within the same form - javascript

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?

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

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

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

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>

Related

Disable button with value after submit

How can I block submit after click? I have form with button submit with value.
<button type="submit" name="submit" value="1" class="btn btn-sm btn-warning" id=""><i class="fa fa-pencil" aria-hidden="true"></I>Save edit</button>
And my JS looks this:
$(function(){
$("form").submit(function (e) {
$(".btn").attr("disabled", true);
return true;
});
});
Button is blocked but form is not submitting, I don't know why?
$(function(){
$("form").submit(function (e) {
$(".btn").attr("disabled", true);
return true;
});
});
Here the line written as return true prevents the form from being sent and leaves it with the true.
This is what should be written.
$(function(){
$("form").submit(function (e) {
$(".btn").attr("disabled", true);
});
});
Edit
Using AJAX
$(function() {
$("#myForm").on('submit', function(event) {
var form = this;
// Prevent native form submit!
event.preventDefault();
// Disable Button
$(".btn").attr("disabled", true);
// Submit form with AJAX
$.ajax({
url: $(form).attr('action'), // URL where we will send the form
data: $(form).serialize(), // Serialize form data automatically,
type: 'POST',
beforeSend: function() {
alert('The form is sent to: ' + $(form).attr('action') + ' \nForm data: ' + $(form).serialize());
},
success: function(response) {
alert(response); //or whatever
},
error: function() {
alert('Failed!\nBecause "' + $(form).attr('action') + '" not a valid URL'); //or whatever
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm" action="//localhost/some-page.html">
<input name="txt" value="TXT" />
<button type="submit" name="submit" value="1" class="btn btn-sm btn-warning" id=""><i class="fa fa-pencil" aria-hidden="true"></I>Save edit</button>
</form>
I thing it is work in your case:
$(document).ready(() => {
$('#yourFormIDhere').on('submit', () => {
$.ajax({
url:"/your_url",
method:"POST",
beforeSend:function() {
$('.btn').attr('disabled', 'disabled');
},
})
});
});
Your question is not really clear,
I don't really understand what you are trying to do.
Do you want the button to be blocked after you click the button and the form to be submitted?
If you are trying to make the form submit then remove
return true;

Jquery order of events

have a button click in a form and have required validation when clicking on that button. I put in
if (!formHandle.valid()) { return; }
in the global site.js file where I want that event to fire first before the event for the actual button. Currently the jquery for the actual button fires first before the global jquery. How can I make sure that the global jquery fires first or is this even possible?
html
<p id="vote-status" class="card-text forum-blue">
#{if (#Model.VoteId != 0)
{
<text>
<br /Text.
<br />Text
</text>
}
else
{
<text><br />Text.</text>
}
}
</p>
#{
if (Model.AvailableVotingOptions != null)
{
#Html.DropDownListFor(m => m.VotingOptionId,
Model.AvailableVotingOptions,
"- Please select -",
new { #class = "form-control", #id = "voting-options" })
}
}
<div class="card-footer">
<div class="row">
<div class="col-sm-12 col-md-3 col-lg-3">
<button type="button"
class="btn btn-success btn-sm col-sm-12"
id="button"
data-action="submit">
<i class="fas fa-vote-yea fa-fw"></i>
#if (#Model.VoteId != 0)
{
<text>Re-Cast Vote</text>
}
else
{
<text>Vote</text>
}
</button>
</div>
</div>
</div>
Site.js (event I want to hit first)
$(document).on("click",
'[data-action="submit"]',
function (e) {
var formHandle = $(this).closest('form');
if (!formHandle.valid()) {
return;
}
if (formHandle.valid()) {
blockUI();
}
});
Document.js
$(document).on("click",
'#button',
function (e) {
e.preventDefault();
var post_url = $("#form-vote").attr("action"); //get form action url
var request_method = $("#form-vote").attr("method"); //get form GET/POST method
var form_data = $("#form-vote");
$.ajax({
url: post_url,
type: request_method,
data: form_data.serialize(),
processData: false,
async: true
}).done(function (objOperations) {
if ($("#validation-error")[0].textContent.trim() === "") {
ShowVoteStatus(true, "Your document is submitted successfully.");
}).fail(function (error) {
ShowVoteStatus(false,
"Your document was not submitted successfully.");
}).always(function (jqXHR, textStatus) {
$.unblockUI();
});;
});
https://codepen.io/bootsy1974/pen/ExggoQg
why do different functions? you can make a check before sending in the second function.
if its possible and this same one button
if its not possible to try after validation use
$("#button").trigger("click");
$(document).on("click",
'[data-action="submit"]',
function (e) {
e.preventDefault();
var formHandle = $(this).closest('form');
if (!formHandle.valid()) {
return;
}
if (formHandle.valid()) {
blockUI();
$("#button").trigger("click");
}
});
but formHandle.valid is not a function
need changed '#button' from button and created another element to binding this function. in another to try sending without validation. need do dependeces sending from validating. but you have to parallel working.
<div class="col-sm-12 col-md-3 col-lg-3">
<div id="button"></div>
<button type="button"
class="btn btn-success btn-sm col-sm-12"
data-action="submit">
<i class="fas fa-vote-yea fa-fw"></i>
#if (#Model.VoteId != 0)
{
<text>Re-Cast Vote</text>
}
else
{
<text>Vote</text>
}
</button>
</div>
and this have not '}'
$(document).on("click",
'#button',
function (e) {
e.preventDefault();
var post_url = $("#form-vote").attr("action"); //get form action url
var request_method = $("#form-vote").attr("method"); //get form GET/POST method
var form_data = $("#form-vote");
$.ajax({
url: post_url,
type: request_method,
data: form_data.serialize(),
processData: false,
async: true
}).done(function (objOperations) {
if ($("#validation-error")[0].textContent.trim() === "") {
ShowVoteStatus(true, "Your document is submitted successfully.");
}}).fail(function (error) {
ShowVoteStatus(false,
"Your document was not submitted successfully.");
}).always(function (jqXHR, textStatus) {
$.unblockUI();
});;
});
https://codepen.io/romanown/pen/QWKKERZ
deleted not worked validating
https://codepen.io/romanown/pen/zYKKKqv

jQuery Ajax POST save delete submit

Here is my code
<form method="post" role="form" id="form" enctype="multipart/form-data" autocomplete="off">
<input type="submit" id="save" name="save" value="Simpan Data Client" class="btn" style="font-size:0.7em; letter-spacing:1px; color:#666666" /> //For save
<input type="submit" id="delete" name="delete" value="Delete Client" class="btn-delete" style="font-size:0.7em; letter-spacing:1px; color:#666666; padding:8px 15px" /> //For Delete
</form>
<script type="text/javascript">
$("#form").on("submit",function (e)
{
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax(
{
url:'Master/Database/Client/RunClient.php',
type: 'POST',
data: formData,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
beforeSend:function()
{
document.getElementById("loading").style.display = "";
},
complete:function()
{
//document.getElementById("loading").style.display = "none";
},
success:function(result)
{
document.getElementById("info").innerHTML = result;
var n = result.search("error");
if(n < 0) /*document.getElementById("form").reset();*/ $(".input").val('');
}
});
});
</script>
I can get all data from inside my form except from Input type submit i make.
I can't use isset($_POST["save"]) and isset($_POST["delete"]) at my RunClient.php
Create separate function for a submit and pass "submit type" depending on what button is clicked;
$('#save').click(function() {
submitForm('save');
});
$('#delete').click(function() {
submitForm('delete');
});
function submitForm(submittype) {
var formData = new FormData();
//push your form data to formData and add the submittype
formData['type'] = submittype
}
in your php file
$submittype = $_POST['type']; // 'save' or 'delete'
if($submittype == 'save') {
//do save action
}
if($submittype == 'delete') {
//do delete action
}
I use to avoid submit inputs and change by buttons.
<button type="button" id="save">SUBMIT</button> //For save
<script type="text/javascript">
$("#save").on("click",function (e)
{
});
</script>
So, if anyone deativates javscript form will not submit.
And you can send the data like this:
data: {
foo: 'var'
foo2: 5
},
EDIT. Sorry missunderstood your question.
Just control with javascript what button is clicked and assign a value with a hidden field.
'$("#form").on("submit",function (e)' replace the function with
$("#save").click(function() {
});
$("#delete").click(function() {
});

Two submit buttons in Ajax.BeginForm. Need to call different js functions in OnSuccess

I have an Ajax form on my MVC page, with two separate submit buttons...
#using (Ajax.BeginForm("Save", "Company", new AjaxOptions() {
HttpMethod="Post", OnSuccess="closeForm"
}, new {#id = "companyEditForm"})) {
....some edit fields......
<input type="submit" value="Save & Next"/>
<input type="submit" value="Save" />
}
I would like to call a different js function after the form is submitted with the "Save & Next" button. So if the user clicks the "Save" button, it should submit the form then call the "closeForm" javascript function. If the user clicks the "Save & Next" button, it should submit the form, then call the "nextForm" javascript function. Is there a simple way of achieving this?
Is there a simple way of achieving this?
No, but you could have the controller action pass the button that was clicked in the result. This could be done either as a Json property (if you are returning JSON) or it could also be a custom response HTTP header.
And then inside your success callback (which can only be one) you could retrieve this value in order to know which button was clicked and act accordingly.
So, start by giving a name to your submit button so that you know which one was clicked:
#using (Ajax.BeginForm("Save", "Company", new AjaxOptions() {
HttpMethod="Post", OnSuccess="onSuccess"
}, new { id = "companyEditForm" })) {
....some edit fields......
<button type="submit" name="btn" value="save_next">Save & Next</button>
<button type="submit" name="btn" value="save">Save</button>
}
And then inside your controller action
[HttpPost]
public ActionResult Save(MyViewModel model)
{
Response.AppendHeader("X-Button", Request["btn"]);
... your usual processing
}
and finally inside your onSucecss callback:
function onSuccess(data, status, xhr) {
function onSuccess(data, status, xhr) {
var btn = xhr.getResponseHeader('X-Button');
if (btn == 'save_next') {
// The "Save & Next" button was clicked
} else if (btn == 'save') {
// The "Save" button was clicked
} else {
// The user didn't submit the form by using the mouse and
// clicking on a button, he simply pressed Enter while
// inside some text field or you have some other portion of
// javascript which triggered the form submission without pressing
// on any submit button
}
}
}
You could switch from Ajax.BeginForm() to Html.BeginForm() and then use JQuery to submit your form.
<script type="text/javascript">
$('#save').on('click', function () {
var form = $('form');
$.ajax({
url: form.attr('action'),
type: 'post',
data: form.serialize(),
success: function (result) {
// call another function
}
});
return false;
});
$('#saveAndEdit').on('click', function() {
$.ajax({
url: form.attr('action'),
type: 'post',
data: form.serialize(),
success: function (result) {
// call another function
}
});
return false;
});
</script>
You can also write something like this:
#using (Ajax.BeginForm("Save", "Company", new AjaxOptions() {
HttpMethod="Post", OnSuccess="closeForm"
}, new { id = "companyEditForm" })) {
<input type="submit" onclick="showNextForm = true;">Save & Next</button>
<input type="submit" onclick="showNextForm = false;">Save</button>
}
...
var showNextForm = false;
function closeForm(data) {
if(showNextForm) {
nextForm();
}
else {
// do your stuff
}
}

Ajax Call before submitting the form

I need to check whether the data is already exists in the database before submitting the form using ajax. The most common scenario is the checking the availability of the username and email.
It's not working but I tested the ajax function without using the from control and it works fine. The project is created in MVC 3 VB.
Javascript:
$('#addSalesPeople').click(function () {
$.post("ajax_functions/checkDuplicate.cshtml",
{
extension: document.getElementById('Extension').value,
initials: document.getElementById('Initials').value
},
function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
});
HTML:
#Using Html.BeginForm("Create", "SalesPeople", FormMethod.Post)
#Html.ValidationSummary(True)
#<fieldset>
............................
..............................
#Html.TextBoxFor(Function(model) model.Extension, New With {.onkeyup = "javascript: charCounter(this,4);", .onblur = "javascript: zeroPad(this, 4)"})
#Html.TextBoxFor(Function(model) model.Initials)
<input id="addSalesPeople" class="btn span2" type="submit" value="Add" />
</fieldset>
-Thanks
You need to observe the submit event of the form.
Instead of
$('#addSalesPeople').click(function () {
use
$('#theFormId').submit(function () {
see: http://api.jquery.com/submit/
You can also disable the form submit and send it later manually:
$( '#theFormId' ).submit( function ( event ) {
event.preventDefault();
/* your AJAX code */
$( '#theFormId' ).submit();
} );
I am posting a real tested code.
HTML: Simple form post button in #using
(Html.BeginForm())
{
//use your text box or other control here
<input type="submit" id="Create" value="Create" class="btn btn-primary" />
}
JavaScript:
<script>
$(document).ready(function () {
$("form").submit(function (e) {
e.preventDefault(); //prevent default form submit
if ($(this).valid()) {
var UserId= $('#UserId').val();
$.ajax({
url: '/Home/CheckUserExist/', //ControllerName/ActionName/
data: {
UserId: UserId
},
success: function (data) {
showMsg(data);
},
cache: false
});
}
});
});
function showMsg(hasCurrentJob) {
if (hasCurrentJob != "OK") {
alert(hasCurrentJob);
return false;
} else {
//if check is ok than from post to controller
$("form").unbind('submit').submit();
}
}
</script>
MVC Controller:
public async Task<JsonResult> CheckUserExist(int UserId)
{
//condition for user check
if (UserExist==true)
{
return Json("User Exist Please choose another user name or etc", JsonRequestBehavior.AllowGet);
}
return Json("OK", JsonRequestBehavior.AllowGet);
}
if you have any query mail me vishalroxx7#gmail.com.

Categories