Disable submit button on click after form validation - javascript

I have a form, which has a jquery form validation.. what i need is the submit button should get disabled when i submit the form once the validation is done..
<form action="#" method="post" id="myform" name="myform">
Location: <input name="location" type="text" />
Site: <input name="site" type="text" />
Age: <input name="age" type="text" />
Gender <input name="gender" type="text" />
<input name="button" type="submit" class="myButton" id="button" value="Submit" />
</form>
here is my form JsFiddle

Not sure why you want to disable the submit button but using jQuery you could do
$('input[type="submit"]').prop('disabled',true);
Typically you either wouldnt have a submit button, or else submit the form and the page will reload!
UPDATE
To stop people from reposting the values by refreshing the page as you wrote in comments, redirect the user to the page without the values posted!
header('/same_page.php');

you want to do the action on form.submit. Not sure if you need to add form.valid() there as a check, but I always do it like that. Afterwards you can return true or false.
True: The browser proceeds with the link and action specified in the form
False: The browser stops (when you have validation errors)
Here the code:
$('#myform').submit(function() {
if (!$('#myform').valid()) return false;
$('#myform input[type=submit]').attr("disabled", "disabled");
return true;
});
I've also updated your fiddle with that code, so you can try it out

after you validate the form, use:
$( "#button" ).click(function(event) {
if($('#myform').valid()) {
$(event.target).attr("disabled", "disabled");
}
});

If you want to disable once the form which you want to validate is valid, then you can disable the submit button like this
$("#myForm").validate({
submitHandler: function(form) {
// do other stuff for a valid form
$('#myform input[type=submit]').attr("disabled", "disabled");
form.submit();
}
});

Related

Validate html form with javascript after html automatic validation

I have to make a little form with some fields like name, age or email. For example:
<input id="name" type="text" required/>
I have a problem with the validation because i want to use the automatic validation of html to check that all fields with the required tag aren't empty and, after that, validate some fields (like the email) with javascript. I have a submit input element like this:
<input type="submit" value="Submit" onclick="form.validate()" />
The problem is that the onclick method (validate()) is always called before the auto validation, and what i want to do is call that method afther the auto validation ends (and it's everything right). The javascript i'm using to test looks like this:
"use strict";
class Form {
constructor(){}
validate(){
alert("validate");
}
}
var form = new Form();
The alert is always shown, but the auto validation it's not. If i don't put the onclick tag with its method on the submit button, the auto validation works. Any idea about my problem?
You need to use the directive ng-submit in your form:
<form ng-submit="form.validate()" ng-controller="YourController">
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
</form>
https://docs.angularjs.org/api/ng/directive/ngSubmit
https://docs.angularjs.org/api/ng/directive/form#submitting-a-form-and-preventing-the-default-action
Keep Rocking!
This method uses jQuery. First you need to prevent the default action on form submit, then you can do your validation, then finally submit the form. Example below.
Your form:
<form id="form">
<input type="text" required>
<input type="submit" value="Submit!">
</form>
Javascript(with jQuery):
$('#form').submit(function(ev) {
ev.preventDefault(); // to stop the form from submitting
/* Validations go here */
form.validate();
alert('here');
this.submit(); // If all the validations succeeded
});
JavaScript(vanilla):
document.getElementById('form').addEventListener('submit', function(ev) {
ev.preventDefault(); // to stop the form from submitting
/* Validations go here */
alert('here');
this.submit(); // If all the validations succeeded
});

Validate input type=number min=... single field, no form [duplicate]

I'm using HTML5 for validating fields. I'm submitting the form using JavaScript on a button click. But the HTML5 validation doesn't work. It works only when then input type is submit. Can we do anything other than using JavaScript validation or changing the type to submit?
This is the HTML code:
<input type="text" id="example" name="example" value="" required>
<button type="button" onclick="submitform()" id="save">Save</button>
I'm submitting the form in the function submitform().
The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.
However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity() method. If you would like to display the same error messages as the browser would do in HTML5 form validation, I’m afraid you would need to check all the constrained fields, since the validityMessage property is a property of fields (controls), not the form. In the case of a single constrained field, as in the case presented, this is trivial of course:
function submitform() {
var f = document.getElementsByTagName('form')[0];
if(f.checkValidity()) {
f.submit();
} else {
alert(document.getElementById('example').validationMessage);
}
}
You should use form tag enclosing your inputs. And input type submit.
This works.
<form id="testform">
<input type="text" id="example" name="example" required>
<button type="submit" onclick="submitform()" id="save">Save</button>
</form>
Since HTML5 Validation works only with submit button you have to keep it there.
You can avoid the form submission though when valid by preventing the default action by writing event handler for form.
document.getElementById('testform').onsubmit= function(e){
e.preventDefault();
}
This will give your validation when invalid and will not submit form when valid.
I may be late, but the way I did it was to create a hidden submit input, and calling it's click handler upon submit. Something like (using jquery for simplicity):
<input type="text" id="example" name="example" value="" required>
<button type="button" onclick="submitform()" id="save">Save</button>
<input id="submit_handle" type="submit" style="display: none">
<script>
function submitform() {
$('#submit_handle').click();
}
</script>
I wanted to add a new way of doing this that I just recently ran into. Even though form validation doesn't run when you submit the form using the submit() method, there's nothing stopping you from clicking a submit button programmatically. Even if it's hidden.
Having a form:
<form>
<input type="text" name="title" required />
<button style="display: none;" type="submit" id="submit-button">Not Shown</button>
<button type="button" onclick="doFancyStuff()">Submit</button>
</form>
This will trigger form validation:
function doFancyStuff() {
$("#submit-button").click();
}
Or without jQuery
function doFancyStuff() {
document.getElementById("submit-button").click();
}
In my case, I do a bunch of validation and calculations when the fake submit button is pressed, if my manual validation fails, then I know I can programmatically click the hidden submit button and display form validation.
Here's a VERY simple jsfiddle showing the concept:
https://jsfiddle.net/45vxjz87/1/
Either you can change the button type to submit
<button type="submit" onclick="submitform()" id="save">Save</button>
Or you can hide the submit button, keep another button with type="button" and have click event for that button
<form>
<button style="display: none;" type="submit" >Hidden button</button>
<button type="button" onclick="submitForm()">Submit</button>
</form>
Try with <button type="submit"> you can perform the functionality of submitform() by doing <form ....... onsubmit="submitform()">
2019 update: Reporting validation errors is now made easier than a the time of the accepted answer by the use of HTMLFormElement.reportValidity() which not only checks validity like checkValidity() but also reports validation errors to the user.
The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.
Updated solution snippet:
function submitform() {
var f = document.getElementsByTagName('form')[0];
if(f.reportValidity()) {
f.submit();
}
}
HTML5 Validation Work Only When button type will be submit
change --
<button type="button" onclick="submitform()" id="save">Save</button>
To --
<button type="submit" onclick="submitform()" id="save">Save</button>
Try this out:
<script type="text/javascript">
function test
{
alert("hello world"); //write your logic here like ajax
}
</script>
<form action="javascript:test();" >
firstName : <input type="text" name="firstName" id="firstName" required/><br/>
lastName : <input type="text" name="lastName" id="lastName" required/><br/>
email : <input type="email" name="email" id="email"/><br/>
<input type="submit" value="Get It!" name="submit" id="submit"/>
</form>

Replace/Hide Input Button If Form Is Validated (Using jquery.validate.js)

I have this normal form:
<form class="vform" action='http://example.com/someaction.php' method='post' id='myid' >
<input type="email" name="email" id="email" class="required email " placeholder="Enter Your Email" >
<input id="#before" type='submit' value="Submit">
</form>
I am using the jquery.validate.js plugin to validate the form, which is working fine. (Link)
WHAT IS REQUIRED:
Before the user is redirected upon successful validation of the form, there is this 'pause' (while its redirecting)... during this time, users are repeatedly hitting the submit button.
How can I hide/replace (maybe with a loading gif or something) the submit button IF the form is validated.
Meaning, disable or replace the input button with something else IF the form is validated.
THE VALIDATION CODE:
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery.validation/1.14.0/jquery.validate.js"></script>
<script>
$(document).ready(function() {
$(".vform").validate();
});
</script>
I tried adding some replacement/disable code after the validate function like this:
$(this).children('input[type=submit]').attr('disabled', 'disabled');
or
$('#before').replaceWith($('#after'));
But confused as to how to actually go about it.
Can anyone offer some insight?
EDIT: The input button shouldn't be replaced/disabled if the form validation is false
You can submitHandler of jQuery validate.
<script>
$(document).ready(function() {
$(".vform").validate({
submitHandler: function(form) { // <- pass 'form' argument in
$("#before").attr("disabled", true);
form.submit(); // <- use 'form' argument here.
}
});
});
</script>

submitting a form via jquery removes submit input variable

Here's my HTML:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="test" method="get" action="">
<input type="hidden" name="var1" value="true" />
<input type="submit" name="var2" value="submit" />
</form>
<script>
$("#test").submit();
</script>
The resultant request that that makes has var1 in it but not var2. My question is why and what can I do to get var2?
Here's a live demo:
http://www.frostjedi.com/terra/dev/submit.php
try: method="post" in form or use <button type="submit"></button>
A form should submit the value of a submit button only if it's clicked to submit the form (see HTML5 4.10.22.4 Constructing the form data set). Calling the submit method doesn't click the button, so it doesn't submit the value.
The code you've posted will endlessly submit the form, thanks.
You can call the click method of the button, but that may not work (i.e. submit the button's value) everywhere:
<form id="test" method="get" action="">
<input type="hidden" name="var1" value="true">
<input type="submit" name="var2" value="submit">
</form>
<button onclick="$('#test')[0].var2.click()">submit form</button>
Or, as user3701524 suggests, use method=post if that suits.
The value on button will only be submitted when u actually CLICK that button. To make it all work nice, I recommend binding to
$('form').on('submit', function(e) {
// here you have the button value if it was clicked.
e.preventDefault(); // optional this prevent default submission.
});
either way, calling $('form').submit() will NOT send the button value because is not triggered by the button itself.
Hope it helps!

submit text field on enter press (AJAX)

I have a search that operates by AJAX. It works perfectly well when the user presses the search button, the problem is... if the user presses enter... it submit the form rather than executing the AJAX javascript function. How can I make the Enter button call my AJAX function as opposed to submitting the form?
Use the form's onsubmit event to execute your ajax call and make the button into a submit button if it isn't already.
Example HTML
<form action="/search.php" onsubmit="submitAjaxQuery(event)">
<input type="text" name="keywords" />
<button type="submit">Go!</button>
</form>
Example JS
function submitAjaxQuery(event)
{
if (event.preventDefault)
event.preventDefault();
else
event.cancel = true;
// run ajax calling function here.
}
Here is a simple DOM way to handle this:
<form action="javascript:void(0)">
<input type="text" />
<input type="submit" onclick="doSomething(this.form)">
</form>
<script>
function doSomething(form){
alert('form submitted');
}
</script>
Place the cursor in the input field, and either if you click the button or type enter, the form is submitted by javascript (not the page)
Trap it in the onSubmit method of the form and return false.
With jQuery:
jQuery("#myform").submit(function() {
callAJAXFunction();
return false;
});
The correct way is to let the non-javascript users use the form submit with page refresh but a javascript call for those with javascript:
<form action="yourscript.php" method="post" onsubmit="doSomething(this.form); return false;">
<input type="text" />
<input type="submit" />
</form>
<script>
function doSomething(form){
alert('form submitted');
}
</script>

Categories