繁体   English   中英

如何将功能从onblur更改为使用Submit按钮的onclick?

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

这是我正在尝试使用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/

window.onload = function () {

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

};

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

此处: 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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