I am writing a code that takes the user input from a form, I've written a javascript code to check whether the fields in the form are empty or not. It is working well, but there is a problem that I've been trying to solve but I couldn't. If there is any empty field the error message occurs properly, but the page reloads immediately after that resetting everything. I've searched the web a lot and tried to return false in the javascript file, or even change the button type to "button", but nothing worked.
Here is the submit button code which is written inside a form,
<input type="submit" value="Update" name="Update" class="submitbutton" >
Here is the javascript file that's used for validation,
var emptyfields=0;// to count the errors
function init()
{
var myForm = document.getElementById( "myForm" ); //calling forms by ID
emptyfields=0;
myForm.onsubmit = check;// if the admin click submit (check function will be called)
myForm.onreset = clear;// if the admin click clear (clear function will be called)
} // end function init
function check()
{
if(document.getElementById("name").value=="")//check if the name filed is empty
{
document.getElementById("invalid_name").innerHTML="You must fill the Name field";
document.getElementById("name").style.borderColor="red";//change the color of the border's filed into red
emptyfields+=1;//increment it to count the error
}
else
{
document.getElementById("invalid_name").innerHTML=""; //set the error message to empty
document.getElementById("name").style.borderColor="black";//return the original border's filed color
}
if(document.getElementById("quantity").value=="") //check if the quantity field is empty
{
document.getElementById("invalid_quantity").innerHTML=" You must fill this field with a number"; //show the quantity error message
document.getElementById("quantity").style.borderColor="red"; //change the boarder color of quantity filed to red
emptyfields+=1; //increment the number of errors
}
else
{
document.getElementById("invalid_quantity").innerHTML=""; //set the quantity error message to "" in order to hide it
document.getElementById("quantity").style.borderColor="black"; //reset the border of the quantity field to black
}
//check if the price field is empty
if(document.getElementById("Price").value=="")
{
document.getElementById("invalid_price").innerHTML=" You must fill this field with a number"; //show the price error message
document.getElementById("Price").style.borderColor="red"; //change the border color of price field to red
emptyfields+=1; //increment the number of errors
}
else
{
document.getElementById("invalid_price").innerHTML=""; //set the price error message to "" in order to hide it
document.getElementById("Price").style.borderColor="black"; //reset the border color of the price field to black
}
if(document.getElementById("image2").value=="") //check if the image field is empty
{
document.getElementById("invalid_image").innerHTML=" You must upload an image"; //show the image error message
emptyfields+=1; //increment the number of errors
}
else
{
document.getElementById("invalid_image").innerHTML=""; //set the image error message to "" in order to hide it
}
if(document.getElementById("Description").value=="") //check if the description field is empty
{
document.getElementById("invalid_Description").innerHTML=" You must fill the Description field"; //show the description error message
document.getElementById("Description").style.borderColor="red"; //change the border color of description field to red
emptyfields+=1; //increment the number of errors
}
else
{
document.getElementById("invalid_Description").innerHTML=""; //set the description error message to "" in order to hide it
document.getElementById("Description").style.borderColor="black"; //reset the border color of the description field to black
}
if (emptyfields >0) //check if there is any input error made by the user
{
return false; //if yes return false
}
else
{
return true; //if no return true
}
}//the end of the check function
function clear()
{
return confirm( "Are you sure you want to reset?" ); //ask the user if she is sure about resetting the fields.
}
window.addEventListener( "load", init, false ); //add a load event listener to the window which triggers init function that calls check and clear functions to perform the validation and reset
can anyone please tell me how to prevent the page from reloading?
Any help is highly appreciated.
Thank you.
The onsubmit callback is called with an event argument which can be used to stop the event triggering its default behaviour. Change your code to:
function check(e) {
// your validation code ...
if(error) {
e.preventDefault();
}
}
You can find out more here.
This is often more desirable than using return false for reasons that are summed up in this answer
You need to return false; by check(). So when an error occurs, it prevents onsubmit from submitting the form.
ie.
myForm.onsubmit = check();
// short version of check
function check() {
...
if(error) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
return false;
}
}
Hope this helps.
Related
I have a grid in which user can add as many rows as he wants and there are two textboxes (Minimum Value & Maximum Value). When the user enters Min and Max value. I am checking whether the range that user has entered is already there in the database. if yes then it shows me an alert. I am doing this on focusout Now the problem is that the alert keeps popping up infinite times when I click from one textbox directly to another textbox. Can anyone help me with this?
Here is the function on my focus out
function CheckValidation(obj) {
var ajx = new AJAXsupport();
ajx.resetVar();
ajx.addData('CL', 'CheckValidation');
var sucSave = function() {
if (ajx.getRefreshText() != "0") {
alert(ajx.getMessage());
$('#btnSave').attr('disabled', 'disabled');
return false;
} else {
$('#btnSave').attr('disabled', false);
}
}
customSave(ajx, sucSave);
}
}
I have multiple input fields and if three fields showing error then focus goes on the last error field.
How to set focus on the first error field and so on. I tried return false; and it is not working. preventDefault() also not working.
This is my js code for the name field and the rest of the field validation is the same as this name field except validation rules.
if (name.length < 1) {
$('#name_error').text(NAME_ERROR);
$('#name').focus();
error = true;
// return false; not working
} else {
var regEx = /^[A-Za-z ]+$/;
var validName = regEx.test(name);
if (!validName) {
$('#name_error').text(INVALID_NAME_ERROR);
$('#name').focus();
error = true;
// return false; not working
} else {
$('#name_error').text('');
error = false;
}
}
Option 1 - Add class to the fields with error and then you can use below code to focus the first error element.
$('.error-class').first().focus()
Option 2 - Create a variable of top of the function and store the ID of the first error field in that. At the end of the validation rules trigger focus for the element ID stored in a variable.
I'm building a registration page and I want the button to be disabled until all of the inputs pass validation. Well I have all of the native validation logic done (missing values, pattern mismatch, etc...), but I wanted to implement a "username taken/available" piece of validation where the button still wouldn't be enabled until the username had valid inputs for all of their inputs AND supplied a desired username that was not already in use.
I have the server call and all of that all done, my only issue is the actual enabling/disabling of the button and assigning the border classes to the inputs. Here is my code for the response from the AJAX call:
ajax.onload = function() {
if (this.responseText === "taken") {
if (username.classList.contains("taken")) {
return;
} else {
username.classList.remove("successBorder");
username.classList.add("errorBorder");
username.classList.add("taken");
}
} else {
if (!username.checkValidity()) {
username.classList.remove("successBorder");
username.classList.add("errorBorder");
return;
} else {
username.classList.remove("errorBorder");
username.classList.add("successBorder");
username.classList.remove("taken");
}
}
}
And then here is the code for where the button is enabled/disabled that is called on the input event for every input element:
function validate() {
if (document.querySelector("form").checkValidity() && !(username.classList.contains("taken"))) {
registerButton.removeAttribute("disabled");
const ruleSpans = document.querySelectorAll("span[data-rule]");
for (span of ruleSpans) {
span.classList.add("hide");
}
for (input of inputs) {
input.classList.remove("errorBorder");
input.classList.add("successBorder");
}
return;
}
registerButton.setAttribute("disabled", "true");
if (this.checkValidity()) {
// Get rid of the error messages
this.classList.remove("errorBorder");
this.classList.add("successBorder");
const ruleSpans = document.getElementsByClassName(this.id);
for (span of ruleSpans) {
span.classList.add("hide");
}
return;
}
// Adding attention borders and error messages based upon what the issue is
this.classList.remove("successBorder");
this.classList.add("errorBorder");
const ruleSpans = document.getElementsByClassName(this.id);
for (span of ruleSpans) {
span.classList.add("hide");
switch (span.getAttribute("data-rule")) {
case "patternMismatch":
if (this.validity.patternMismatch) {
span.classList.remove("hide");
}
break;
case "valueMissing":
if (this.validity.valueMissing) {
span.classList.remove("hide");
}
break;
case "typeMismatch":
if (this.validity.typeMismatch) {
span.classList.remove("hide");
}
break;
}
}
}
And right now, the disabling/enabling works IF it's the first time on input for that element, but it is "behind" all of the times after the first time. (for example, if the username is taken, the register button is enabled, but if the username is taken, the register button is disabled, the exact opposite of what I want happening).
So I thought, instead of checking for it the correct way (the way I did it in the code !(username.classList.contains("taken"))), I would reverse the logic to look like this: username.classList.contains("taken"). And that works (even though it is logically wrong and incredibly hack-y), EXCEPT for the first time a taken username is had.
What am I doing logically wrong here?
I would suggest you to have a code structure like this
function serverValidation () {
//make the ajax call here to validate all server validation
//send the success callback handler to 'clientValidations'
}
function clientValidations(){
//validate other form elements that does not require a server request here
//Then submit the form through an ajax form submit
submitFormThroughAjax();
}
function submitFormThroughAjax() {
//submit the form through ajax.
}
function onSubmit(event) {
event.preventDefault();
serverValidation();
}
//Here onSubmit should be attached to the form submit handler.
Refer:below link to know how to submit a form through ajax.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
This example does all the validations only after the user submits but if you want the errors to be shown instantaneously as the user interacts you need to handle it through specific form element events.
I have an image that is kind of a spinner that is displayed to a user on submitting a form.
So in js.coffe I do something like this:
$('.button.save-btn.btn.btn-primary').click ->
$('.loader').show()
And if the form fails validations and an error is shown, at that time I hide the same image, like this:
$('#error-box').show();
$('.loader').hide();
The spinner works fine when an error is encountered but now what if when the user is clicking on the submit button when the form is empty. How do I handle that event? Where exactly do I hide the spinner image in this case?
I hope I explained my query properly, any help will be much appreciated. Thanx in advance:)
I don't use coffee personally but in plain js you could check if the fields have a value before showing the spinning image:
$('.button.save-btn.btn.btn-primary').click(function(){
var form_compiled = false;
//iterate trough each input field
$("#MyformID").find("input, textarea").each(function(){
//check if input field has a value or is empty
if ($(this).val() != ""){
form_compiled = true;
}
})
// and then show the image if at least a filed is filled
if ( form_compiled == true){
$('.loader').show()
}
})
the code above works if the user fills at leas a field.
If you want to run the check on just some mandatory fields you could add them the class "required", for example, then run the js check on those classes:
$('.button.save-btn.btn.btn-primary').click(function(){
var form_compiled = true; << change initialization
$("#MyformID").find(".required").each(function(){
//check if input field is empty
if ($(this).val() == ""){
form_compiled = false; //set to false is a required field is empty
}
})
if ( form_compiled == true){
$('.loader').show()
}
})
i have disabled the submit button in my guestbook. it has 2 fields[name(textbox)&comment(textarea)].it has 2 other fields ID(primary key) and date.the function is:
function Frmvalidate() {
var nmchk=document.forms["guestform1"]["name"].value;
var cmntchk=document.forms["guestform1"]["comment"].value;
if (nmchk.length==0)
{
var namep = document.getElementById("namep");
namep.innerHTML="name must be filled out";
return false;
}
else if (cmntchk.length==0)
{
var cmntp = document.getElementById("cmntp");
cmntp.innerHTML="comment must be filled out";
return false;
}
else
{
document.getElementById("sbmt").disabled=false;
return true;
}
}
i have called the function in places: body tag's onload,button tag's onclick. still its not working and blank entries are being stored in my database.
You dont need to disable the submit button
you gain noting from it. ( alerting the user , running another script etc...)
instead -- The submit button should stop its regular behaviour by this code :
<input type="submit" onclick="return Frmvalidate();"/>
meaning :
when you press the button , it will execute the function yielding True or False and if it's True (only) it will continue to the server.