I'm still a newb when it comes to MVC, Ajax and JavaScript. I have an application where I have to make a change. Right now, when a change is made and the Save, the spinner displays as the info saves and the page loads. The code for the Save looks like this:
$('#SaveButton').on('click', function () {
navParams.isDirty = false;
});
HTML looks like this:
<input type="submit" value="Save" class="btn btn-block btn-primary user-action" name="action:Save" id="SaveButton" />
Just a note there multiple buttons on the screen so it is using the "Multiple Button" solution from How do you handle multiple submit buttons in ASP.NET MVC Framework?
The following code was added:
$('#SaveButton').on('click', function () {
navParams.isDirty = false;
displaySavePromptMessage();
});
function displaySavePromptMessage() {
if (isModalOpen == false) {
bootbox.dialog({
closeButton: false,
title: "",
message: "<strong>Warning: </strong>Changes have been made, ensure corresponding dates have been updated on the screen",
buttons: {
success: {
label: "Ok",
callback: function () {
navParams.userAction = false;
}
}
}
});
}
}
Now what's happening is the save button is clicked, the spinner starts running, the dialog box loads, but before the OK button is clicked the dialog button closes and the spinner stops. The changes are saved.
What needs to happen is the spinner starts, the dialog box loads and everything stays as is until the user clicks OK. Then the processing continues. I'm not sure how to make this happen. Any thoughts?
Basic concept. You need to listen to submit event and prevent it:
$('.some-form').on('submit', function(submitEvent) {
submitEvent.preventDefault();
});
Then in your handler, you need to submit your form on success:
// Inside your success handler
$('.some-form').get(0).submit();
You have input type="submit" which will submit the form when this button is clicked. Either change this to type="button" or as #Lesha Ogonkov said
$('#yourFormID').on('submit', function (e) {
e.preventDefault();//it will stop loading page on form submission
});
in ajax inside you success handler function
$('.myFromID').get(0).submit();
Related
In my semantic UI form (<div class="ui form">) it appears every button triggers the form validation, even if it is not a submit button.
Two different kind of buttons below:
<button class="ui blue right labeled icon primary submit button">
<i class="right arrow icon"></i>
Submit
</button>
and
<button class="ui blue button">
Something Else
</button>
both of these are inside the semnatic UI form element. both trigger my validation rules (standard setup rules) :
$('.ui.form')
.form({
fields: {
example:: {
identifier: 'example',
rules: [
{
type : 'empty',
prompt : 'Please enter at least one thing'
}
]
}
}
}
)
;
Only "Solution" I could find online was creating a button like this:
<input type="button" class="ui blue button">
Test
</input>
but this doesn't put the text ("test") inside the button, also couldnt get the size of the button to be same as other ones.
Is there a way to get it to not trigger my validation? Pretty stumped on why a non submit button is doing it.
Simply define the type of the button. Default type is submit:
<Button type="button" />
Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Attributes
I was able to implement this in a different way, as the button type=button control while ignoring the validations, did not submit, and if I did submit manually the default event handler of semanticui would intervene and show the validation errors.
My use case two buttons, one a save draft and the other a finalize (final save). The first one had to save the data as is, without triggering the validations, while the other would trigger validations and then save.
I am also implementing all the validators using data attributes that I custom implemented for this project, hence the form validator is inside a JS file.
In my form validation's failure method, I included a delegate function which I could set on my page and depending on which button clicked it, then be able to return true or false.
My form validator inside a JS file
$('.ui.form').form({
inline: true,
on: 'submit',
fields: formFields,
transition: 'fade',
keyboardShortcuts: false,
onFailure: function () {
var returnValue = false; //Default to false, since validations failed
//If the delegate is present, fire it to evaluate
if (typeof window.delegValidate == 'function') {
returnValue = window.delegValidate();
}
//Ignore the toast if the delegate evaluated to TRUE
if (!returnValue) {
$('body')
.toast({
title: 'Unable to save',
message: 'Please enter all required field data before saving.',
classProgress: 'red',
showProgress: 'top',
progressUp: true,
position: 'bottom right',
showIcon: 'red exclamation triangle'
});
}
return returnValue; // false is required if you don't want to let it submit
}
});
and on my page I attached a function to the window, since my form validation is inside a JS file.
Page function
//For all postback buttons, save the id value in a hidden field for use in the delegate
$('.postbackButton').bind('click', function (e) {
$('#ButtonClicked').val(this.id); // a hidden field on the page
});
//setting the delegate for use in the form validations
window.delegValidate = function () {
//For the save button, just ignore the validations and return true
//This in turn is invoked by the failure method of the form validation that is
//dynamically attached to the page, and hence this return value is respected
//over the false that is otherwise sent back for when we want to interrupt the page
//since there are errors normally.
if ($('#ButtonClicked').val() == 'Save')
return true;
else // if value is finalize, let it return false
return false;
}
For other pages where I don't want this functionality, I can simply not write the delegate method and the default validation fires as expected on the submit button.
Hope this helps someone still looking for a way to do this. :)
I'm simply trying to find a way to create a confirm dialog in jquery to use in place of the default confirm function in javascript. I have a confirm dialog that's used to decide if I want to proceed without a given value in a form. The whole program is here:
http://nowlin.com/testpop.php
The button code that's giving me a headache looks like this, but it may not be the button code. I'm just learning jquery:
buttons: {
'Yes': function() {
document.getElementById("clicked").value = "true";
creturn = true;
$(this).dialog('close');
},
'No': function() {
document.getElementById("clicked").value = "false";
creturn = false;
$(this).dialog('close');
}
}
This program works fine except for the confirm dialog. I've tried setting a variable that has a global scope (creturn), and a DOM element from a hidden input (clicked.value), so that when the dialog closes I can tell which button was chosen. The values both get set, but not until after the form Send button, where the onclick event is located, is hit a second time:
<button type=submit name=clicked value=true onclick='return chkreq("cfbform")'>Send</button>
The behavior is, if you enter an email address and no name, and hit the Send button, the confirm dialog pops up. If you select Yes the dialog closes, but the form isn't submitted. If you click the Send button a second time, the dialog pops up again, immediately closes on its own, and the form is submitted. Clearly I'm missing something.
Thanks for any insights.
I would switch the button from type=submit to type=button (we can also drop the return)
<button type=button name=clicked value=true onclick='chkreq("cfbform")'>Send</button>
and then use jQuery to submit the form when it passed validation.
function chkreq(fid) {
// both values are set return true
if (document.getElementById(fid).elements.namedItem("name").value.length > 0 &&
document.getElementById(fid).elements.namedItem("email").value.length > 0) {
document.getElementById("clicked").value = "true";
$('#' + fid).submit();
}
...
}
And
buttons: {
'Yes': function() {
document.getElementById("clicked").value = "true";
$('#' + fid).submit();
$(this).dialog('close');
},
'No': function() {
document.getElementById("clicked").value = "false";
creturn = false;
$(this).dialog('close');
}
}
For more info see https://api.jquery.com/submit/
The other option used on that page is binding to the submit event. With your override-able validation via the popup, I think the above code will be easier to implement.
using Submit buttons and binding click events to them and handling the click in jQuery could cause issues like your jquery gets called then the post pack gets called because of the submit.
I suggest change the type of the button from "submit" to "button" and give it a try.
I have a simple HTML button on my form, with script as follows:
$(document).ready(function () {
$("#btn1").click(function () {
$("#btn1").text("Button clicked");
return false;
});
});
With the return false, it works as I expect - I click the button, and its text changes to 'Button clicked'. Without the 'return false', it changes, but then changes back.
Complete JQuery noob here, why do I need the 'return false'?
A <button> in a form submits the form, which is why it turns back, the page reloads resetting everything javascript changed, so you see the change, and it immediately reloads the page when the form submits.
The return false prevents the form from submitting when clicking the button.
Note: the <button> element has a default type of submit, so it will always submit the form it's nested inside.
Like #adeneo said, your form is being sent out so the page will reload. Additionally, if you don't want to use return false; you can use preventDefault() by passing an event parameter to your function as such:
$(document).ready(function () {
$("#btn1").click(function (ev) {
ev.preventDefault();
$("#btn1").text("Button clicked");
});
});
Hope this helps,
If the <button> was not intended to submit the form, then instead of using return false; or other workarounds make the button the proper type.
<button id="btn1" type="button">
And it will stop submitting when clicked. The reason it does now is because the button's default type is submit (it has 3 possible types: submit, button, and reset).
Question: How to handle consecutive button clicks in jQuery. For example I am submitting the form to server but in the meantime user clicks button again then duplicate request has been generated for the same. How to handle this efficiently in jQuery.
HTML Code:
<a id="submitBtn" href="javascript:void(0);"
onclick="login.validateLogin();"
class="btn btn-lg btn-success btn-block">Login</a>
jQuery code:
var login = {
validateLogin:function(){
$("#errormsg").hide();
login.validate();
if($('#loginForm').valid() === false){
return;
}
$("#submitBtn").prop('onclick',null);
/* Server request */
},
validate:function(){
$("#loginForm").validate({
ignore:"",
submitHandler: function(form) { return false; }
});
},
}
Disable the <submit> button or any other button which on clicked, submits the form, so only first click gets counted and the end user is prevented from clicking it. It is also semantic way of doing as just unbinding any event associated with the button while still allowing to click, will in some way confuse the users.
$("#loginForm").validate({
ignore: "",
submitHandler: function(form) {
$('#submitBtn').prop('disabled', true); // disable so it won't be clicked
return false;
}
});
Not sure why you have the .validate() method inside a function like that. The .validate() method is supposed to be called once and only used for initializing the plugin.
You should use a type="submit" button so that you can properly integrate with the plugin and enable/disable it much easier than trying to manually capture/deactivate/activate an anchor element. (Use CSS on the button element to make it look exactly like your anchor element.)
Then use .prop('disabled', 'disabled') within the submitHandler to disable the button as soon as the properly validated form is submitted.
As you can see by the demo, most of your code was not needed as the plugin takes care of nearly everything automatically.
$(document).ready(function() {
$("#loginForm").validate({ // <- initialize plugin on form
ignore: [], // <- proper way to set ignore to nothing
submitHandler: function(form) {
$('#submitBtn').prop('disabled', 'disabled');
alert('submitted'); // <- for demo
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>
<form id="loginForm">
<button id="submitBtn" class="btn btn-lg btn-success btn-block">Login</button>
</form>
I'm working with jQuery and I have implemented a button click handler. To test, I have been setting a console output with the contents "test". However, when clicking on the button, the output appears in the console, but only for a brief moment before disappearing again. That repeats every time the button is clicked.
JS code:
$(document).ready(function () {
$("#go").click(function () {
console.log("test");
});
});
HTML code:
<form class="navbar-form navbar-right">
<button id="go" class="btn btn-default">Go</button>
</form>
Is there a solution to this?
That's because the button submits the form and reloads the entire page in your browser. Cancel the default action of this button by returning false from your click handler if you want to stay on the same page and continue executing some javascript code:
$(document).ready(function () {
$("#go").click(function () {
console.log("test");
return false;
});
});
If you do not cancel the default action, the browser will simply redirect away leaving no time for any javascript stuff to run.