简体   繁体   中英

I am checking if a field is empty in an HTML form, but only the first 'if' statement is executed and then it refreshes the page

Only the first " if " statement is executed for firstName , not the second " if " statement for lastName and no alert for the error message - just refreshes the page.

function checkformGiftVoucher() {
    var errormessage = "";

    if (document.getElementById('firstName').value == "") {     
        errormessage += "First name \n";
        document.getElementById('firstName').style.borderColor = "red";
     }
    if (document.getElementById('lastName').value == "") {
        errormessage += "Last name \n";
        document.getElementByName('lastName').style.borderColor = "red";
    }
    if (errormessage != ""){        
      alert("Please complete the following fields: \n" + errormessage);
      return false;
    }
    else {
      /*submit*/
    }

you must use

event.preventDefault();

this code prevent refresh page.

and for display the error message and submit you must use this code:

function checkformGiftVoucher() {
    event.preventDefault();

    var errormessage = "";
    var flag = true;

    if (document.getElementById('firstName').value == "") {
        errormessage += "First name \n";
        document.getElementById('firstName').style.borderColor = "red";
    }
    if (document.getElementById('lastName').value == "") {
        errormessage += "Last name \n";
        document.getElementByName('lastName').style.borderColor = "red";
    }
    if (errormessage != ""){
        flag = false
        alert("Please complete the following fields: \n" + errormessage);
    }

    if(flag == true) {
        /*submit*/
    }

}

I think you should use this:

document.getElementById('lastName').style.borderColor = "red";

instead of:

document.getElementByName('lastName').style.borderColor = "red";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM