这是我正在尝试使用submit按钮的一段代码。 它在onblur上可以正常工作,但是当我尝试使用带有提交按钮的onclick时不起作用。 我怎样才能做到这一点?

这是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>

这是纯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();

    }
}

这是JSFiddle的现场直播: http : //jsfiddle.net/kyAY5/

===============>>#1 票数:0

window.onload = function () {

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

};

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

===============>>#2 票数:0

此处: http//jsfiddle.net/kyAY5/4/

window.onload = function () {

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

};

也,

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

这将仅显示一次redalert

  ask by user3529194 translate from so

未解决问题?本站智能推荐: