0

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.

John Cartwright
  • 5,109
  • 22
  • 25
Dania
  • 67
  • 3
  • 12

2 Answers2

1

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.

daxeh
  • 1,083
  • 8
  • 12
  • Thank you so much for your answer, but I've done that in this line, 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 } But it doesn't work, do you have any other solutions please? – Dania May 14 '15 at 15:51
  • Combine it with @Rich because I realized you have attached a window listener – daxeh May 14 '15 at 15:53
  • @Dania: I've updated the example combining RichieAHB suggestion, reason due to listener added // which does init(), trigger()...validate(). Hope this helps – daxeh May 14 '15 at 15:59
  • should onsubmit = function()? hmm.. ie. `check()` is different from `check` – daxeh May 14 '15 at 16:35
  • Yes I've tried that, but still not working, it's ok, I've used HTML 5 required attribute to solve the problem. Many thanks – Dania May 16 '15 at 09:54
1

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

Community
  • 1
  • 1
RichieAHB
  • 2,030
  • 2
  • 20
  • 33
  • Thank you so much for your answer, can you please tell me what object e represents? – Dania May 14 '15 at 15:52
  • It represents the arguments passed to the `onsubmit` callback. A callback will be run by the "parent code", which can pass it some parameters. It doesn't matter if you pass a callback that doesn't use them but it *can*. You don't chose the parameters of a callback, they are given to you by whatever piece of code is running it. Have a look at this answer to hopefully clear it up: http://stackoverflow.com/a/13004118/609907 – RichieAHB May 14 '15 at 15:55
  • Thank you, I really appreciate your help. But, I've tried this and the same problem still exists, please if there is any other solution let me know – Dania May 14 '15 at 16:21
  • Have a look at this fiddle ... there shouldn't be any reason that it doesn't work? http://jsfiddle.net/sxzcjxtj/4/ – RichieAHB May 14 '15 at 16:35
  • It's ok, I've used HTML 5 required attribute to solve the problem. Many thanks – Dania May 16 '15 at 09:54