asp.net mvc disable submit button if form is invalid - javascript

Is there a way to disable/submit the form submit button if the form has validation errors in such a way that the user can click it only if the form is valid.
I'm using unobtrusive validation with "remote" attribute validation with ASP.Net MVC 4 and razor.
Thanks and best regards

Depends on where you are doing your validation. If you are doing it server side with jquery you can add e.preventDefault to the check if it is invalid and the button click won't fire until your conditions are met. If you are doing server side validation using attributes then you can check model state like
if (ModelState.IsValid){
}else{
}
and if the model state is valid (the data passes all the checks) run one set of code. If the model state is invalid then just return view to go back to where you started and pass a message with whatever failed for the user. Hopefully this helps.
Update:
just saw the edit on your comment. For an ajax call you will want to use prevent default.
$('.SubmitButton').on('click', function(e){
$.ajax({
//your call
success: function(result){
if(result.false){
e.preventDefault();
alert(result.message);
}
}
});
});
so if the call is successful the submit call will go through. If it is false then jquery will stop the button click and you can then display a message or do something else.

Related

Avoid multiple form submit in html

I'm facing a sort of dummy problem.
On my site there is an order form (simple html form) and I noticed that I get double commands from time to time.
I realized that if I clicked repeatedly few times the submit button (before the action page is loaded) I got as many commands as I have clicked.
So I wonder if there are simple solution to make form submission asyncronous?
Thanks
P.S. I added JQuery UI dialog on submit "wait please..." but I get still double commands.
UPDATE
As GeoffAtkins proposed I will:
disable submit after dialog is shown
make use of unique form's token (as it is already added by Symfony) Do not use Symfony token as unique form token as it is always the same for current session. Use just random or something like that.
I would consider doing this (jQuery since you said you used that)
$(function() {
$("#formId").on("submit",function() {
$("#submitBut").hide();
$("#pleaseWait").show();
});
});
if you submit the form and reload the page.
If you Ajax the order, then do
$(function() {
$("#formId").on("submit",function(e) {
e.preventDefault();
var $theForm = $(this);
$("#submitBut").hide();
$("#pleaseWait").show();
$.post($(this).attr("action"),$(this).serialize(),function() {
$theForm.reset();
$("#submitBut").show(); // assuming you want the user to order more stuff
$("#pleaseWait").hide();
});
});
});
NOTE that disabling the submit button on click of the submit button may stop the submission all together (at least in Chrome): https://jsfiddle.net/mplungjan/xc6uc46m/
Just disable the button on click, something like:
$("#my-button-id").on("click", function() {
$(this).attr("disabled", "disabled");
});
var bool = true;
function onclick()
{
if(bool)
{
//do stuff
bool = false;
}
else
{
//ignore
}
}
You could disable the button on the form when it is clicked, and then continue to perform the action. You would probably change the text to say "loading..." or some such.
You may also want to re-enable the button on fail or complete of the ajax request.
I've done this many times similar to this: https://stackoverflow.com/a/19220576/89211

Javascript confirm box not able to submit form on selecting yes

In jsp , clicking on button called sumbitForm() function as below
document.Data.formSubmit.value="Yes";
document.Data.action.value='SUMBIT';
document.Data.submit();
here giving proper result and setting value as occured on controller
In same JSP, calling onload function ,In that checking if command class variable set = occured then only confirmation box can show and after clicking yes button of confirmation box then request should process.. I used document.Data.submit() but its not working and not giving exception.
i think this will help you
if(confirm("Are you sure you want to submit the form ") == true ){
// then submit the form
}

How to submit (or not submit) a form based on the result of an Ajax request?

I have a form on my site where users submit stuff and get results
<form accept-charset="UTF-8" action="/submit-stuff" data-remote="true" method="post">
<!-- various form fields -->
<input type="submit" value="Run Code" id="submit-button">
</form>
Before submitting their info to the backend, I try to get the results in Javascript. If I can get the results, I return false in Javascript to prevent the form submission.
$('#submit-button').click(function() {
if(canGetResults()){
//deal with submission and then
return false;
}
//the button will work as usual if canGetResults is false or there's an error
});
This works fine, but now I want to try to get the results through another ajax request and only submit to my regular backend if that fails. I call the following code after the button is clicked:
$.post("http://example.com/submit-stuff", json, function(data) {
//do stuff with data
});
However, it's asynchronous (so I can't return results from it) so the code reaches return false even when the other ajax attempt fails. How should I fix this so it only submits to my own backend when the ajax attempt failed?
I could change the $.post to $.ajax and make it synchronous, but that's not usually recommended. Alternatively, I can submit the form within the $.post callback, but how should I submit the whole form from there? And would it still submit if there's an error or http://example.com/submit-stuff doesn't work?
Your submit handler should always prevent the form from submitting.
Then, if the Ajax code comes back with an OK, you should call the form's submit() method. This will bypass the submit handler and submit the form.
NB: Call submit on the DOM object, not the jQuery object. jQuery has a habit of triggering event handlers from its wrappers.
You can bind the ajax request all in your submit function, and call a .post() event if necessary:
$("form").submit(function(e){
e.preventDefault(); // <-prevents normal submit behaviour
//only post if your ajax request goes your way
$.ajax(url,function(data){
//argument to post or not
if(data=="success"){ postForm(); }
});
});
function postForm(){
$.post(
"/submit-stuff"
,$( "form" ).serialize()
,function(data){
//your code after the post
});
}
If you do not want to create a separate function for your postForm, then you can just put it inside the wrapper where it's currently being called.

jQuery validation - multiple groups

Im designing a user control that has the following:
a textbox called 'AddressInput'
a google maps plugin
a linkbutton
a textbox for the marker title called 'MarkerTitleInput'
a "Submit" button
The problem is this:
When the linkbutton is clicked, I need to validate that AddressInput was completed, but nothing else
When the submit button is clicked, I need to validate that AddressInput and MarkerTitleInput were both completed.
So my first two problems are:
1) How do i validate certain fields from a linkbutton, without submitting the form
2) How do i validate all fields from the form being submitted
My other problem is that when the linkbutton is clicked, my code runs a lookup against Google's Geocode to get an address. I was going to create an additional validation method to handle when an address is not found, but using a validator means the json request is sent everytime a key is pressed, which is too much - i only want the validation to run when the linkbutton is clicked. I have tried (selector).validate({ onkeyup:false }) with no avail. Is it perhaps possible to manually set whether the .valid() method thinks the form is valid?
Thanks
Al
$("form").validate({
groups:{
pg1:"_Phone1 _Phone2 _Phone3",
pg2:"dob_month dob_day dob_year"
},
errorPlacement:function(error, element){
if(element.attr("name")=="_Phone1"|| element.attr("name")=="_Phone2" || element.attr("name")=="_Phone3"){
error.insertAfter("#_Phone3")
}
else if
(element.attr("name")=="dob_month"|| element.attr("name")=="dob_day" || element.attr("name")=="dob_year"){
error.insertAfter("#dob_year")
}
else
error.insertAfter(element);
},
});
});
Give each of the two buttons a unique class (for ease of targeting in jQuery).
Give each class an OnClick event.
Validate in the OnClick event.
If the validation succeeds, return true.
Else return false.

jQuery Forms - Ajax and normal submit the same form

I have a confirm step in one of my pages.
Desired action:
user clicks 'submit' and an AJAX request is made that does the appropriate action and returns a confirm dialog
user 'confirms' and then the form is submitted using a standard post.
So for the first part I'm fine using the jQuery form plugin:
$('form').ajaxForm(...options...);
For the second part I'd like to submit the form again, but non-ajax. Basically I want to do this:
$('form').submit();
And have it do an actual browser post. The problem is that $('form').submit() just triggers the ajax submit.
Is there a way to use the form for both purposes?
$('forms-submit-button').click()
..does that work , for the second submit?
:) :)
Can't you just unregister the submit event handler after you've ajax-posted the results? Why do you need to post the same data twice, by the way? If the data haven't changed between the Ajax post and the regular one, why is the regular one needed?
You can try to change a value in the form (se some hidden value to 1), do another ajax request and finally do a redirect. It's not the same but it should work.
Note that it's very strange to submit the same data twice though..
Answered by Surya as a comment (if you check this question again please post the answer so I can mark it!)
$('forms-submit-button').click() ..does that work , for the second submit?
form onsubmit='ajaxCheck();'
...
/form
script
var ajaxCheck = function()
{
//do check
return confirm(); // if ok form submit normaly / if cancel form doesn't submit
}
/script
or something with a flag:
var flag = true;
var firstCheck = function()
{
if( flag )
{
//do the ajax Call which will fire an event,
// let's call it onData
$.post(url,{param1:val1,...,paramN:valN},onData);
return false;
}
return true;
}
var onData = function (data)
{
flag = !confirm(...);
//if user click ok and try to re-submit the form
//this time will just go
}

Categories

Resources