Javascript If else statement trouble within a Function Validate() -
the following script should validate input fields depending on selection user makes in drop-down box (var problem).
the trouble i'm having when if statement runs problem == 4 (below) , user has filled in corresponding cityid field, alert (alert#3) next if statement (problem == 5) triggered. want alert#3 trigger if user has selected problem == 5 drop-down , has not filled in model field.
the same trouble happens respectively when if statement runs problem == 5.
function validatesor() { var user = document.sor.user; var problem= document.sor.problem; var cityid = document.sor.cityid; var errors1 = document.sor.errorcodes1; var model = document.sor.model; var errors2 = document.sor.errorcodes2; var software = document.sor.softwaretype; if (user.value == "") { window.alert("please enter name."); user.focus(); return false; } if (problem.selectedindex < 1) { alert("alert#1"); problem.focus(); return false; } if (problem.selectedindex == 4) { cityid.focus(); } else if (cityid.value == "") { alert("alert#2"); cityid.focus(); return false; } if (problem.selectedindex == 5) { model.focus(); } else if (model.value == "") { alert("alert#3"); model.focus(); return false; } if (problem.selectedindex == 6) { software.focus(); } else if (software.value == "") { alert("alert#4"); software.focus(); return false; } return true; }
you're not returning function when discover problem #4. thus, because is 4, it's not 5, , "else" part of branch taken.
edit — ok, let's @ code:
if (problem.selectedindex == 4) { cityid.focus(); } else if (cityid.value == "") { alert("alert#2"); cityid.focus(); return false; } if (problem.selectedindex == 5) { model.focus(); } else if (model.value == "") { alert("alert#3"); model.focus(); return false; }
if index 4, happens? code runs:
cityid.focus();
then what? code proceeds next if
statement:
if (problem.selectedindex == 5) {
now, if got through noticing index 4, chances equal 5? zero! thus, comparison guaranteed false
, move else
part. apparently, "model.value" empty string, if
statement succeeds. alert.
i think problems solved bringing logic of code more in line logic of validation process:
if (problem.selectedindex == 4 || cityid.value == "") { cityid.focus(); return false; }
that way, if index 4 or if city id value empty, you'll treat error city id , exit function. won't matter comes after that, because return
leaves function @ point.
Comments
Post a Comment