以下是我尝试使用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/
答案 0 :(得分:0)
window.onload = function () {
document.getElementById("firstname").onblur = mandatoryField;
document.getElementById("lastname").onblur = mandatoryField;
document.getElementById("submitBtn").onclick = mandatoryField;
};
答案 1 :(得分: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
一次。