Reputation: 15
I am trying to make my text boxes red when the value is null. Unfortunately when I submit the form only the text box emp_id
turns red and the emp_fn
remains the same. I think this is because of the return false
function. What do you think. Btw Im a newbie
function emp_add_validate() {
var emp_id = document.emp_add.emp_id.value;
var emp_fn = document.emp_add.emp_fn.value;
if (emp_id == null || emp_id == ""){
document.getElementById("emp_id").classList.add("is-invalid");
return false;
}
if (emp_fn == null || emp_fn == ""){
document.getElementById("emp_fn").classList.add("is-invalid");
return false;
}
}
Upvotes: 0
Views: 199
Reputation: 932
Yes it is because of the return
keyword.
The return statement ends function execution and specifies a value to be returned to the function caller.
What happen is when the first if
block is executed it saw the return
keyword and exits the function which makes the second if
to not get executed.
You can refractor your code by having the return false
statement outside of the if
block.
function emp_add_validate() {
var emp_id = document.emp_add.emp_id.value;
var emp_fn = document.emp_add.emp_fn.value;
if (emp_id == null || emp_id == ""){
document.getElementById("emp_id").classList.add("is-invalid");
}
if (emp_fn == null || emp_fn == ""){
document.getElementById("emp_fn").classList.add("is-invalid");
}
return false;
}
Upvotes: 0
Reputation: 66957
Perhaps you meant to return false
if either if-test fails, but only after you have performed both tests:
function emp_add_validate() {
var emp_id = document.emp_add.emp_id.value;
var emp_fn = document.emp_add.emp_fn.value;
var ok = true;
if (emp_id == null || emp_id == "") {
document.getElementById("emp_id").classList.add("is-invalid");
ok = false;
}
if (emp_fn == null || emp_fn == "") {
document.getElementById("emp_fn").classList.add("is-invalid");
ok = false;
}
return ok;
}
Upvotes: 3