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:
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)
My example code with indenting..
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:
There are probably better ways of doing it than this.
Better than nothing mind you!
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..
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"); } } }
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; }
Better than nothing mind you!
Total Comments 0