Joshua Tuonan
Joshua Tuonan

Reputation: 15

Return False wont read the next IF Statement?

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

Answers (2)

elpmid
elpmid

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.

from mdn web docs

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

cybersam
cybersam

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

Related Questions