LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Blogs > 3vra
User Name
Password

Notices


Rate this Entry

Java script checking form elements

Posted 02-03-2009 at 02:53 PM by 3vra

I understand your code but it does'nt do what I want it require.

Quote:
Originally Posted by gn000we View Post
You have nested the ifs!

Also it helps to indent the code too, so you can see what it's doing.

(a cutting from your code, indented)
Code:
for(i=0; i<document.inventory_sys.elements.length; i++)
{
   if (document.inventory_sys.elements[i].type == "checkbox")
   {
      if (document.inventory_sys.elements[i].checked == false)
      {
          if (document.inventory_sys.elements[i].type == "text")
          {

etc..
My example code with indenting..

Code:
if (myVar == "123")
{
   alert("Hello, I am 123");

   if (theOtherVar == "456")
   {
       alert("Hello, I am 456");
      
       if (myVar == "789")
       {
           alert("Hello, I am 789");    
       }

   }   

}
You will never see the message "Hello, I am 789" as myVar is already = "123".

I haven't tested this code, but..
I presume this is what you need:

Code:
function validate_required (){
   
   //We are setting a boolean variable to return if empty form
   var blnRetReady = true; //valid, unless made false!

   //Note: Two pipe symbols (SHIFT + \) means 'or', two ampersands mean 'and', and two equals mean 'equal to', etc.

   for(i=0; i<document.inventory_sys.elements.length; i++){
      if ((document.inventory_sys.elements[i].type == "checkbox") &&
(document.inventory_sys.elements[i].checked == false))
      {
          blnRetReady = false;
      }

      if ((document.inventory_sys.elements[i].type == "text") && (document.inventory_sys.elements[i].value == ""))
      {
          blnRetReady = false;
      }

   }
   
   //Alert the user that the form is not valid
    if (!blnRetReady){
       alert ("Nothing has been entered");
    }

   //You may want to return this boolean aswell
   //This stops the form submitting
   //Make sure that the js event on the element has return too e.g. 
   //<INPUT type='submit' value='Send' onClick='return validate_required();'>

   return blnRetReady;

}
There are probably better ways of doing it than this.
Better than nothing mind you!
Posted in Uncategorized
Views 1928 Comments 0
« Prev     Main     Next »
Total Comments 0

Comments

 

  



All times are GMT -5. The time now is 07:48 AM.

Main Menu
Advertisement
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration