Preventing resetting of form after js rejected validation - javascript

I have a survey that on button submit the first thing it runs in my js is validation if required fields are entered. Basically:
if (x == null) {
alert("You forgot to enter a required field!.");
return false;
};
Is there any way from preventing the page from refreshing/resetting what has previously been filled out if they forgot one required field?
This survey stores to local storage if that matters or can be used to help here.

You could use Jquerys .submit function (if using Jquery):
$('#formID').submit(function(){
if (x == null) {
alert("You forgot to enter a required field!.");
return false;
}
});

Handle on submit event during form submission and return false in handler method.

Check these answer first:
How to validate with Javascript an Input text with Hours and Minutes
Form Validation using JavaScript
Validate email address textbox using JavaScript
if you're not interested in using a framework like jQuery this is how it could be done:
<form name="form" onsubmit="return validate()">
function validate() {
var input_value = document.forms["form"][" .. input name .. "].value;
if( input_value == '' ) return false;
}
If you have multiple inputs, I would suggest looping through them with a foreach loop.
With jQuery it would be something like:
$( '#formID' ).on( 'submit', function() {
event.preventDefault();
// check input value
if( valid input ) $( this ).submit();
});
Interesting read: return false vs preventDefault

Related

prevent form submission (javascript)

I have a form with a text input:
<form name="form1">
<cfinput type="text" name="text1" id="text1" onChange="someFunc();">
</form>
I only want it to submit in certain cases. (I run some error-checking first)
<script>
function someFunc() {
if (1==2) {
document.form1.submit();
} else {
alert("Not submitting");
}
</script>
The problem is: even though the alert is triggering fine, somehow, the form is still submitting (There are no other submit statements aside from the one!).
Many thanks if anyone can shed some light on this . . .
There's a fundamental flaw with this approach. You are currently telling the form that when text1 changes, then call someFunc(). If true, use JavaScript to submit the form. If false, go on about your business. If you hit enter in the text input, the form still submits. If there is a submit button that gets clicked, the form still submits.
The basic way to approach this is like so:
<form name="form1" onsubmit="return someFunc()">
<input type="text" name="text1" id="text1">
</form>
When the from is submitted, call someFunc(). This function must return either true or false. If it returns true, the form submits. If false, the form does nothing.
Now your JavaScript needs a slight alteration:
<script>
function someFunc() {
if (1==2) {
return true;
} else {
alert("Not submitting");
return false;
}
}
</script>
You can still have other functions called when a field is changed, but they still won't manage the form's final submission. In fact, someFunc() could call the other functions to do a final check before returning true or false to the onsubmit event.
EDIT: Documentation on implicit form submission.
EDIT 2:
This code:
$(document).ready(function(){
$("#text1").on('change', function(event){
event.preventDefault();
});
});
is stopping the default processing for the change event associated with that element. If you want to affect the submit event, then you'd do this:
$(document).ready(function(){
$("#form1").submit(function(event){
event.preventDefault();
});
});
Which would allow you to do something like this:
$(document).ready(function(){
$("#form1").submit(function(event){
if ( $('#text1').val() !== "foo" ) {
alert("Error");
event.preventDefault();
}
});
});
var form = document.getElementById("Your Form ID");
form.addEventListener("submit", function (e) {
if ("Your Desired Conditions.") {
e.preventDefault();
}
});
use the following code it will work perfectly fine
<form onsubmit="return false;" >

Add validation to HTML5 required fields

I am using HTML5's required attribute on my input elements and select boxes and PHP for validation.
How can I show an alert if the required fields are not filled in? I tried using onsubmit() but the form is processed anyway and no alert is shown.
If the user's browser supports html5, he cant submit the form if not all the required fields have been written into.
Generally, you can prevent a form from submitting in jQuery like so:
$('#yourformselector').submit(function(event) {
$(this).find('[required="required"]').each(function() {
if (!$(this).val().length) {
event.preventDefault();
return false;
}
});
});
If you are using a modern/newer web browser, your default browser alerts should automatically display.
Or try:
$(document).ready(function() {
$('form').submit(function() {
var incomplete = $('form :input').filter(function() {
return $(this).val() == '';
});
//if incomplete contains any elements, the form has not been filled
if(incomplete.length) {
alert('please fill out the form');
//to prevent submission of the form
return false;
}
});
});
You may use checkValidity(), it will try to validate with attributes like pattern, min, max, required, etc. Follow this link to go deeper here
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
alert('invalid input')
} else {
alert('valid input')
}
}
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>

Prevent action attribute from running php script with javascript [duplicate]

This question already has answers here:
prevent form from POSTing until javascript code is satisfied
(4 answers)
Closed 9 years ago.
Is there a way that I can use javascript to prevent a form from runing a php script. For example something like this:
<form action="somePage.php" method="POST>
<input type= "text" class= "field" name = "blah">
<input type="submit" value="Send" >
</form>
I know how to validate what's in that text box using javascript, but I want to prevent the somePage.php to run if the text box is empty. I haven't really tried anything cause I just don't know how to do it.
Hope you guys understand my problem.
Thanks
You can attach function to submit event of the form:
document.getElementById('form-id').addEventListener("submit", function(e){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null){
e.preventDefault();
alert('Pls fill the required fields.');
return;
}
return true;
});
OR
Below solution uses inline js:
If you want to run your js function before submitting the form to php script, you can use onsubmit attribute of the form,
<form id="form-id" action="somePage.php" method="POST" onsubmit="return formSubmit();">
<input type= "text" class= "field" id="field1" name = "blah">
<input type="submit" value="Send" >
</form>
In formSubmit function you can check the value of the input, if its empty or not, and if empty, then you can just return false;
var formSubmit = function(){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null)
return false;
else
return true;
}
You simply need to return false for your submit event by grabbing the form (I used querySelector because you have no IDs or classes), and adding a submit listening event to return false.
var x = document.querySelector("[method='POST']");
x.addEventListener("submit",function() {
return false;
});
Use this code to prevent form from submitting:
var first_form = document.getElementsByTagName('form')[0];
first_form.addEventListener('submit', function (e) {
e.preventDefault(); //This actually prevent browser default behaviour
alert('Don\'t submit');
//Do your stuff here
}, false);
Better read docs
you could in your somePage.php have this be a clause somewhere new the beggin:
if(empty($_POST['blah'])){
die();
}
or the inverse of
if(!empty($_POST['blah'])){
//do what this php is supposed to
}
else{
//display error
}
this will prevent your php from running if that field is not filled out.
Personally I return them to the same page setting some error on the page.

Prevent form submission in java script after displaying alert message

This is my coding in js
var ck_name = /^[A-Za-z0-9 ]{3,12}$/;
function validate(form)
{
var Name = document.getquote.name.value;
if (!ck_name.test(Name))
{
alert("Enter a valid FirstName containing alphabets ,numbers with minimum of 3 characters");
document.getElementById('name').focus();
return false;
}
}
Iam calling this function on form submit. After showing the alert message, I want the focus to be back on the name-textbox but the page get submitted after the alert. The "return false" command is not working.
You add this code when false occurs
$('#formID').attr('onsubmit','return false');
Another Way
$("form").submit(function () { return false; }); that will prevent the button from submitting or you can just change the button type to "button" <input type="button"/> instead of <input type="submit"/>
#Sridhar R answer worked for me, with a little change, instead of 'onsubmit' I used 'onSubmit'
$('#formID').attr('onSubmit','return false');

Displaying an image after pressing submit html

I have the following code to display an image after i press submit
<img id="image1" src="images/Coverflow1.jpg" style="display:none;"/>
<input type="submit" name="submit" value="submit" onclick="$('#image1').show()"/>
Name is retrieved by
var y=document.forms["myForm"]["fname"].value;
Where fname is
<h4>Name: <input type="text" name="fname" size="61" /></h4>
Only problem is this is using Jquery, so I can't seem to pass it through any of my other
validations like checking if the name field is null.
if (name==null || name=="")
{
alert("First name must be filled out");
return false;
}
Is there a Javascript equivalent to this that I can stick in my else statement so it will only show it if the form actually submits properly passing the validation checks beforehand?
Thanks
do all that in jquery.
if (name==null || name=="")
{
alert("First name must be filled out");
return false;
}
else
{
$('#image1').show()
}
You should be using the .submit() event handler of jQuery instead of attaching an onclick property to the submit button. The onclick property will not fire its function in the event that a user submits the form via the enter key; however, the .submit() method will capture it as well.
$("form[name=myForm]").submit(function(e) {
//get value of name here.
var name = this.fname.value; //this refers to the form, because that is what is being submitted.
//Do validation.
if (name == null || name == "") {
//If failed, then prevent the form from submitting.
alert("First name must be filled out.");
e.preventDefault();
return;
}
//If validation passed, show image.
$("#image1").show();
});
First, remove the onclick attribute from the submit button:
<img id="image1" src="images/Coverflow1.jpg" style="display:none;"/>
<input type="submit" name="submit" value="submit" />
Since you're using jQuery, attaching handlers to click events in JavaScript is a snap (and it's also a good practice).
I almost always use the following pattern for form validation (and on the submit of the form, rather than the click of the submit button because there are other ways to submit forms than clicking the button).
$(document).ready(function () {
var formIsValid = function formIsValid () {
// your validation routines go here
// return a single boolean for pass/fail validations
var name =document.forms.myForm.fname.value;
return !!name; // will convert falsy values (like null and '') to false and truthy values (like 'fred') to true.
};
$('form').submit(function (e) {
var allGood = formIsValid();
if (!allGood) {
e.preventDefault();
}
$('#image1').toggle(allGood); // hide if validation failed, show if passed.
return allGood; // stops propagation and prevents form submission if false.
});
});

Categories