简体   繁体   中英

How to change a function from onblur, to onclick with submit button?

Here is a piece of code that I'm trying to make work with submit button. It works fine with onblur, but when I try to use onclick with submit button it doesn't work. How can I do that?

Here is the HTML

Name
<br>
<input size="16" placeholder="First Name" id="firstname" name="firstname" type="text">
<br>
<br>Last Name
<br>
<input placeholder="Last Name" name="lastname" id="lastname" type="text">
<br>
<br>
<button type="submit" id="submitBtn" name="submit">Submit</button>

Here is pure javaScript

window.onload = function () {


    document.getElementById("firstname").onblur = mandatoryField;
    document.getElementById("lastname").onblur = mandatoryField;

};
// Clear potential alert
function clearalert() {

    var redalert = document.getElementById("redalert");
    if (redalert) {
        document.body.removeChild(redalert);
    }
}
//Reset white background
function resetWhiteBackground(elem) {
    elem.parentNode.setAttribute("style", "background-color: #ffffff");

}



function textAlert(txt) {

    // Create the alert node
    var textNode = document.createTextNode(txt);
    redalert = document.createElement("div");
    redalert.setAttribute("id", "redalert");
    redalert.setAttribute("class", "alert");
    redalert.setAttribute("style", "color: red");


    // append node to div and to document
    redalert.appendChild(textNode);
    document.body.appendChild(redalert);
}

function mandatoryField() {


    clearalert();

    // check for missing field
  if (firstname.value.length == "" ) {
        if (lastname.value.length == "") {
      textAlert("You must enter either you first name or last name before submiting");
        }
    } else {
 resetWhiteBackground();

    }
}

Here is it live with JSFiddle: http://jsfiddle.net/kyAY5/

window.onload = function () {

    document.getElementById("firstname").onblur = mandatoryField;
    document.getElementById("lastname").onblur = mandatoryField;
    document.getElementById("submitBtn").onclick = mandatoryField;

};

http://jsfiddle.net/kyAY5/1/

Here: http://jsfiddle.net/kyAY5/4/

window.onload = function () {

    document.getElementById("firstname").blur= mandatoryField;
    document.getElementById("lastname").blur= mandatoryField;
    document.getElementById("submitBtn").onclick = mandatoryField;

};

Also,

var redalert = document.getElementById("redalert");

This will show redalert only once.

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