Disabling Button After First Click Ajax.BeginForm with Javascript - javascript

Having an issue hiding/disabling the submit button with it also submitting the form. I have tried adding: onclick="this.value='Submitting, Please Wait.'; this.disabled='disabled';" into the input submit field which will disable the button but wont submit the form. I have tried placing this into the javascript portion also and it not working. I have tried things like this also:
$("#SignInButton").one('click', function (event) {
event.preventDefault();
$(this).prop('disabled', true);
});
I am at a loss because a lot of examples I am looking at are for html.beginform and this old form was set up with Ajax.BeginForm. Any insight on how to either just hide the button or disable the button with the code below would be much help!!
<div id="LoginModal" style="display:none;padding:1rem;max-width:580px;">
#using (Ajax.BeginForm("Login", "Accounts",
new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "OnSuccess",
OnFailure = "OnSuccess"
}))
{
<div>
Other Form Data
<div>
#Html.Hidden("ItemID", Model.ItemID)
<input type="submit" id="SignInButton" data-loading-text="Signing in" class="button success" value="Sign In" />
</div>
</div>
}
<script type="text/javascript">
var ready;
ready = function () {
$(".fancybox").fancybox({
'content': $('#LoginModal'),
'onStart': function () { $("#LoginModal").css("display", "block"); },
'onClosed': function () { $("#LoginModal").css("display", "none"); }
});
};
$(document).ready(ready);
$(document).on('page:load', ready);
</script>
EDIT!!!!!
<div id="LoginModal" style="display:none;padding:1rem;max-width:580px;">
#using (Ajax.BeginForm("Login", "Accounts", new AjaxOptions { HttpMethod = "POST", OnSuccess = "OnSuccess", OnFailure = "OnSuccess" }))
{
<h1>Sign In</h1>
var displayLocalLogin = "";
#Html.AntiForgeryToken()
#Html.ValidationSummary(false, "", new { #class = "text-error" })
#Html.Sitecore().FormHandler()
<div class="">
<div class="row">
<div class="internal">
<div class="medium-12 columns">
</div>
<div class="medium-12 border-top columns">
<div class="form-group">
<label for="UserName">UserName <span class="required">*</span></label>
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
</div>
</div>
<div class="medium-12 columns">
<div class="form-group">
<label for="Password">Password <span class="required">*</span></label>
#Html.PasswordFor(m => m.Password)
#Html.ValidationMessageFor(m => m.Password)
</div>
</div>
<div class="medium-12 columns" style="padding-bottom: 10px;">
<div class="form-group">
</div>
</div>
<div class="medium-5 columns left">
<div class="form-group">
<div>
<div>
#Html.Hidden("ItemID", Model.ItemID)
<input type="submit" id="SignInButton" data-loading-text="Signing in" class="button success" value="Sign In">
</div>
</div>
</div>
</div>
</div>
#if (string.Equals(System.Configuration.ConfigurationManager.AppSettings["EnableSalesForceLogin"], "true", StringComparison.InvariantCultureIgnoreCase))
{
displayLocalLogin = "displaynone";
#Html.Partial("/salesforceloginpartial.cshtml")
}
</div>
</div>
}
<script type="text/javascript">
$("#SignInButton").one('click', function (event) {
$(this).prop('disabled', 'disabled');
});
//function OnSuccess(data) {
// alert(data);
// $('#LoginModal').parent.html(data).css("display", "block");
// $("#LoginModal").css("display", "block");
//}
var ready;
ready = function () {
$(".fancybox").fancybox({
'content': $('#LoginModal'),
'onStart': function () { $("#LoginModal").css("display", "block"); },
'onClosed': function () { $("#LoginModal").css("display", "none"); }
});
};
$(document).ready(ready);
$(document).on('page:load', ready);
</script>

You can disable the button in the next event loop excecution by using setTimeout(func, 0):
$("#SignInButton").one('click', function (event) {
setTimeout(function() {
event.preventDefault();
$(this).prop('disabled', true);
}, 0);
});
This will block the button right after the user click, but it will pass the first click.

I think you should set the attribute disabled to "disabled" instead
$(this).prop('disabled', 'disabled');

You can probably try to make use of ajaxStart and ajaxStop methods from jquery.
http://api.jquery.com/ajaxStart/
http://api.jquery.com/ajaxStop/
May be something like, in ajaxStart disable the button.

You need to submit the form after disabling button.
Give to your form an id:
#using (Ajax.BeginForm("Login",
"Accounts",
new AjaxOptions { HttpMethod = "POST", OnSuccess = "OnSuccess", OnFailure = "OnSuccess" },
new { id = "formId"}))
and then submit it by javascript:
$("#SignInButton").one('click', function (event) {
event.preventDefault();
$(this).prop('disabled', true); //disable button
$("#formId").submit(); //submit the form
});

Related

Bootstrap 5 form validation doesn't fire

I have a form for allowing the user to change their account password, like so:
<div class="signup-form-small">
<form method="post" name="frmPassword" id="frmPassword" class="needs-validation" novalidate>
<div class="form-group">
<div class="col form-floating">
<input type="password" class="form-control" id="curpwd" name="curpwd" required>
<label class="form-label" for="curpwd">Your Current Password</label>
</div>
</div>
<div class="form-group">
<div class="col form-floating">
<input type="password" class="form-control" id="newpwd" name="newpwd" required>
<label class="form-label" for="newpwd">Enter New Password</label>
</div>
</div>
<div class="row form-group">
<div class="col form-floating">
<input type="password" class="form-control" id="cnfpwd" name="cnfpwd" required>
<label class="form-label" for="cnfpwd">Confirm New Password</label>
</div>
</div>
<div class="form-group">
<button type="submit" id="btnPwdSubmit" name="btnPwdSubmit" class="btn btn-primary btn-lg btn-block w-100 has-spinner">
<div class="spinner-border float-right hidden" id="pwdspinner" role="status"></div>
Change My Password
</button>
</div>
</form>
</div>
In my script I have the following code block which should universally handle validation:
$(document).ready(function () {
'use strict';
window.addEventListener('load', function () {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
});
and finally, here is the script code that fires when the user clicks the 'Chnage My Password' button in the form:
$('#frmPassword').submit(function (event) {
event.preventDefault();
setPwdDisabled();
var obj = Object.fromEntries(new FormData(event.target));
if (obj.Is_Body_HTML == 1) {
obj.Is_Body_HTML = true;
}
else {
obj.Is_Body_HTML = false;
}
if (obj.Is_Active == 1) {
obj.Is_Active = true;
}
else {
obj.Is_Active = false;
}
if ($('#curpwd').val() != $('#cnfpwd').val()) {
$('toastPwd').toast('show)');
return;
}
var json = JSON.stringify(obj);
var request = $.ajax({
url: "../handlers/changepwd.ashx",
method: "POST",
data: json,
dataType: "json"
});
request.done(function (msg) {
if (msg.Success == false) {
$('#spnPwdErr').html(msg.Status);
$('#toastPwdFail').toast('show');
}
else
$('#toastPwdSuccess').toast('show');
});
request.fail(function (jqXHR, textStatus) {
$('#spnPwdErr').html('Unable to complete your request at this time.');
$('#toastPwdFail').toast('show');
});
request.always(function (jqXHROrData, textStatus, jqXHROrErrorThrown) {
setPwdEnabled();
});
});
For whatever reason, the form validation never fires, and I don't know why. I added alerts into the validation code and they never pop up. The form submission happens no matter what. I don't get any errors or other messages in the console. Can anyone shed any light on why this is not functioning?
Remove the add event listener - having it inside the jquery ready makes it redundant -
$(document).ready(function () {
'use strict';
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
});

Disable button once its being clicked on after Ajax - ASP.NET MVC5

I have a form in ASP.NET MVC5 that uses FormMethod.Post I have a Create button that submits the form, but how would I get it to work so that if you click Create then it disables the button. I have tried:
onclick="this.disabled = true"
But then the form is not submitted, hower when it is removed it allows you to add multiple records when clicking Create
This is my code for the form:
#section scripts {
#Scripts.Render("~/bundles/jqueryajaxval")
#Scripts.Render("~/bundles/jqueryval")
<script language="javascript" type="text/javascript">
// cancel
$(document).on("click",
"#CancelForm",
function(e) {
var uri = '#Html.Raw(Url.Action("Index", "Membership"))';
window.location = uri;
e.preventDefault();
});
// submit
$(document).on("click", "#submitMembership", function(e) {
// Perform Ajax request to check if CAE/IPI Number is unique.
var caeipinumber = $('#addMembershipCAEIPINumber').val();
if (caeipinumber) {
$.ajax({
url: '#Url.Action("IsCAEIPINumberUnique", "Membership")',
data: ({ 'caeipinumber': caeipinumber, 'personaIdToIgnore': null }),
type: 'POST',
async: false,
cache: false,
success: function(result) {
if (result.toLowerCase() == "false") {
// Number is not unique and already exists, so display validation error to the user.
e.preventDefault();
$('#addMembershipForm').validate().showErrors({ 'CAEIPINumber': 'CAE / IPI Number already exists!' });
return false;
}
return true;
},
error: function(xhr, status, error) {
}
});
}
});
</script>
}
#section additionalStyles {
}
#section modal {
}
<article class="row">
<h1 class="pageTitle artistHeader fw200 mb20 mt10">#ViewBag.Title</h1>
<div class="col-md-1"></div>
<div id="createMembership" class="col-md-10 formContainer">
<div class="panel">
<div class="panel-heading">
<span class="panel-title">
<i class="glyphicon glyphicon-pencil"></i> Details of New Membership
</span>
</div>
#using (Html.BeginForm("AddMembership", "Membership", FormMethod.Post, new { id = "addMembershipForm", role = "form", #class = "theme-primary form-horizontal" }))
{
<fieldset>
<legend style="display: none">Add Membership Form</legend>
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="panel-body p25 fill bt0 pbn">
<div class="form-group">
#Html.LabelFor(x => x.MembershipName, new { #class = "control-label col-md-3" })
<div class="col-md-8">
#Html.TextBoxFor(x => x.MembershipName, new { id = "addMembershipName", #class = "form-control", placeholder = "Enter Membership Name..." })
#Html.ValidationMessageFor(x => x.MembershipName, string.Empty, new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(x => x.CAEIPINumber, new { #class = "control-label col-md-3" })
<div class="col-md-8">
#Html.TextBoxFor(x => x.CAEIPINumber, new { id = "addMembershipCAEIPINumber", #class = "form-control", placeholder = "Enter CAE / IPI Number..." })
#Html.ValidationMessageFor(x => x.CAEIPINumber, string.Empty, new { #class = "text-danger" })
</div>
</div>
</div>
<div class="panel-footer">
<div class="text-center">
<input type="button" class="btn btn-primary" id="CancelForm" value="Cancel" />
<input id="submitMembership" type="submit" class="btn btn-primary" value="Create" />
</div>
</div>
</fieldset>
}
</div>
</div>
<div class="col-md-1"></div>
</article>
You should listen the form submit event, the submit input used trigger the form submit event and when the event is triggered you can disable the Button you clicked.
$("#form1").submit(function (){
$("#submitbtn").prop ("disabled",true);
$.ajax({requestprops,success:function(){
$("#submitbtn").prop ("disabled",false);
}});
});
This should work:
<script>
function setDisable(id) {
document.getElementById(id).disabled=true;
};
</script>
<input id="submitMembership" type="submit" onclick="setDisable(this.id)" class="btn btn-primary" value="Create" />
First, I would remove the binding on the click of the submit button and instead bind on the submit event.
Replace your submit button function with the following:
$("#addMembershipForm").submit(function (e) {
var submitButton = $(this).find(':input[type=submit]').prop('disabled', true); // Find and disable the submit button
// Perform Ajax request to check if CAE/IPI Number is unique.
var caeipinumber = $('#addMembershipCAEIPINumber').val();
if (caeipinumber) {
$.ajax({
url: '#Url.Action("IsCAEIPINumberUnique", "Membership")',
data: ({ 'caeipinumber': caeipinumber, 'personaIdToIgnore': null }),
type: 'POST',
async: false,
cache: false,
success: function(result) {
if (result.toLowerCase() == "false") {
// Number is not unique and already exists, so display validation error to the user.
submitButton.prop('disabled', false); // Enable submit button
e.preventDefault(); // Do not submit form
$('#addMembershipForm').validate().showErrors({ 'CAEIPINumber': 'CAE / IPI Number already exists!' });
}
},
error: function(xhr, status, error) {
}
});
}
});
var submitButton = $(this).find(':input[type=submit]').prop('disabled', true);is used to find and then disable the button.
It will then do your unique check the same as you had in your original question. However, we will enable the submit button if it returns false so the user can re-submit.

Block Editor for CheckBox MVC with Javascript

You have a button that calls to a Modal window...
Agregar Producto <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
this is the javascript that executes it
<script type="text/javascript">
$(document).ready(function () {
$('#agregarproducto').click(function (e) {
e.preventDefault();
var $link = $(this);
var title = $link.text();
$('#AgregarProducto.modal-title').html(title);
var url = $(this).attr('href');
$.get(url, function (data) {
$('#AgregarProducto .te').html(data);
$('#AgregarProducto').modal();
$('#editorfocus').focus() // set focus
});
});
});
</script>
and the partial view looks like this ...
It is looking to put the EditorFor "disabled" and the checkbox unchecked (false) when the modal is executed, and in the case that the user checks the checkbox to unblock the text box in question ... it also seeks to validate that when they press the "submit" button of the form, validate that the checkbox is marked or unmarked .... in case it is marked, a value will be verified in the ... otherwise it will send the message
"You must enter a quantity or uncheck the box"
I have the following modal view "AgregarProducto.cshtml"...
<h2>Agregar Producto</h2>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>
<div class="form-group">
<div class="col-md-10">
<label>Agregar Cantidad</label>
<input type="checkbox" name="checkcantidad" id="idcheckcantidad" value="false" />
#Html.EditorFor(model => model.d_Cantidad, new { htmlAttributes = new { #class = "form-control", id = "editorprecio" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Kn_CodigoProducto, "Producto", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Kn_CodigoProducto, new { htmlAttributes = new { #class = "form-control", #autofocus = "true" , id = "editorfocus" } })
<div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button class="btn btn-success" id="mybtn" type="submit">
Agregar Producto
<i class="glyphicon glyphicon-ok"></i>
</button>
</div>
</div>
</div>
}
</body>
</html>
and I have the following script in the main view...
<script type="text/javascript">
$(function () {
var st = $("#idcheckcantidad").attr('checked');
$("#idcheckproveedor").change(function () {
st = this.checked;
if (st) {
$("#txtSearch").prop("disabled", false);
}
else {
$("#txtSearch").prop("disabled", true);
}
});
$("#mybtn").click(function () {
if (st && ($("#txtSearch").val() == "" || $("#txtSearch").val() == null)) {
alert("Debe Ingresar una cantidad o desmarcar la casilla");
return false;
}
});
});
</script>
My code does not do anything ... when opening the modal, only the focus defined in the button that opens the modal is executed, but I am not able to block the EditorFor from the modal view and obviously my validation does not work, I am setting the code correctly? , what's going on? any help for me?
PS: when changing the script to my modal window "AddProduct.cshtml" nothing happens either
you can use begin form and keep your form content in it and on submit call the javascript function to validate it. if validation is successfull then return true from that method otherwise prevent form submit
#using (Html.BeginForm("method", "controller", FormMethod.Post, new { enctype = "multipart/form-data", onsubmit = "validateForm(event)" }))
{
// HTML form COntent goes here
}
javascript code for validation
<script>
function validateForm(event)
{
//default is validation fail
var isValid = false;
// validation rules goes here - update isValid value to true if pass else fail
// your code here
// check whether form valid
if(!isValid) {
//if validation fails then prevent submit
event.preventDefault();
}
return isValid;
}

Ajax script not working on Form Submit?

I have an issue, I am loading a partial page however I dont want the form on this page to redirect when I click the save button.
Not sure if I am using the script the correct way, I want to Post to the controller when I click submit but I want to be redirected back to the same page I was on (AdminPanel/AdminProfile) and not redirected to a different controller/view (Account/Manage).
AdminProfile View:
<div id="tab-2" class="tab-pane">
#{Html.RenderPartial("~/Views/Account/Manage.cshtml");
}
</div>
Not sure if my script should go in this view or stay in the partial view?
Controller:
public ActionResult Manage(LocalPasswordModel model)
{
//....
return Json(new { redirectTo = Url.Action("AdminProfile", "AdminPanel") });
}
Partialview with script:
#model LocalPasswordModel
#{
ViewBag.Title = "Change Password";
}
<section class="hgroup">
<div class="panel-body">
<ul class="breadcrumb pull-right top-right">
<li>You're logged in as <strong>#User.Identity.Name</strong></li>
</ul>
<ul class="message-success">#ViewBag.StatusMessage</ul>
#using (Html.BeginForm("Manage", "Account", FormMethod.Post, new { id = "SavePassword", #class = "form-horizontal" }))
{
<div class="social_sign">
<h3>Change your password.</h3>
</div>
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<div class="form-group">
<label class="col-sm-2 control-label">Old Password</label>
<div class="col-sm-10">
#Html.PasswordFor(m => m.OldPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">New Password</label>
<div class="col-sm-10">
#Html.PasswordFor(m => m.NewPassword, new { #class = "form-control"})
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Confirm Password</label>
<div class="col-sm-10">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-sm-12 col">
<input type="submit" class="btn btn-primary pull-right" value="Change password" />
</div>
</div>
}
</div>
</section>
Script in the view above:
#section Scripts {
<script>
$('#SavePassword').submit(function ()
{
if ($(this).valid())
{
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result)
{
if (result.redirectTo)
{
window.location.href = result.redirectTo;
}
else
{
$(".tab-2").html(result);
}
},
error: function ()
{
}
});
}
})
</script>
#Scripts.Render("~/bundles/jqueryval")
}
Nothing seems to happen all I get is an empty page with {"redirectTo":"/AdminPanel/AdminProfile"} in it. Which is the url: http://localhost:57239/Account/Manage
you should change your code like these:
<script>
$('#SavePassword').submit(function ()
{
if ($(this).valid())
{
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result)
{
if (result.redirectTo)
{
window.location.href = result.redirectTo;
}
else
{
$(".tab-2").html(result);
}
},
error: function ()
{
}
});
}
return false;
})
</script>
You have already attached the AJAX call, but forgot to prevent the default submission event. So, use event.preventDefault():
$('#SavePassword').submit(function (e) {
e.preventDefault();
// Rest of your code.
if ($(this).valid())

Form serialization always returns empty string

I have a dropdown in my view. Based on the selection, i insert a partial view into a div (placeholder) in view. Below is the View.
<div class="container">
<div class="row">
<div class="col-lg-4"><p class="lead">What do you want to do?</p></div>
<div class="col-lg-8">
<select id="myDropDown">
<option id="0" selected>I want to..</option>
<option id="1">Reset my password</option>
</select>
</div>
</div>
<div id="partialPlaceHolder" style="display:none;"> </div>
<script type="text/javascript">
$(document).ready(function () {
$('#myDropDown').change(function () {
/* Get the selected value of dropdownlist */
var selectedID = $(this).find('option:selected').attr('id');
/* Request the partial view with .get request. */
$.get('/Requests/FindPartial/' + selectedID, function (data) {
/* data is the pure html returned from action method, load it to your page */
$('#partialPlaceHolder').html(data);
/* little fade in effect */
$('#partialPlaceHolder').fadeIn('fast');
});
});
});
So when I select, "Reset my password" in the dropdown, I am successfully inserting my partial view into the div in my view. Below is my partial view.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-lg-12">
<div class="well well-lg" style="text-align:left">
<div class="form-horizontal" id="resetpasswordform">
<h4>Reset Password</h4>
<hr />
<div class="form-group">
#Html.LabelFor(model => model.ServersList, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ServerName, new SelectList(Model.ServersList))
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserName, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" id="submitButton" value="Reset" class="btn btn-default" />
</div>
</div>
</div>
</div>
</div>
</div>
}
<script>
$(function () {
$("#submitButton").click(function () {
debugger;
$.ajax({
type: "POST",
url: "Requests/Do_ResetPassword",
data: $("#resetpasswordform").serialize(),
success: function (data) {
debugger;
},
error: function (jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
});
});
</script>
The problem is when the submit button is clicked, and I make the ajax post call, the $("#resetpasswordform").serialize() is always "" (empty string).
I tried making the view just with one element. I verified that the elements have name attribute for serialize to work. I also confirmed that I don't have a type=submit in my button. I changed the resetpasswordform into a form instead of div. I even rendered the partial view directly in Index.cshtml without dynamically populating. Nothing fixed the problem. All the time it returns empty string.
I verified all other similar questions in SO and not getting any hint on what i am doing wrong. Please help.
How about you set the id in the form tag:
#using (Html.BeginForm("action", "controller", FormMethod.Post, new { Id = "resetpasswordform" }))
and remove it from the div.

Categories