此JavaScript检查name-text
框是否为空。
如果为空,则同一行应附加“名称是必需的”。
function checkFields(){
var name = document.forms["contact-form"]["name"].value;
if(name == ""){
}
<!--- This is the html code for text box for name and submit button to call checkFields() method -->
<div class="required-fields">
<label>My Name:</label>
<input type="text" name="name"/>
</div>
<input type="button" onclick="checkFields()" value="Send Message"/>
答案 0 :(得分:0)
我觉得你只需要placeholder
html属性,google it。
并且,您首先选择的方法可能不是必需的,仍然请检查updated fiddle,
function checkFields(){
var name = document.forms["contact-form"]["name"].value;
console.log(name);
if(name == ""){
document.getElementsByClassName('error-text')[0].innerHTML='Name field required'
}
else{
document.getElementsByClassName('error-text')[0].innerHTML='';
}
}
答案 1 :(得分:0)
尝试使用placeHolder:或使用input required方法。如果您需要附加一些错误,请参阅以下代码段:
<强> 段: 强>
function checkFields(){
var name = document.forms["contact-form"]["name"].value;
if(name =="" ){
document.getElementById("input").placeholder = "**Name required**";
document.getElementById("error").innerHTML ="**Name required**";
}
}
&#13;
<!--- This is the html code for text box for name and submit button to call checkFields() method -->
<form name="contact-form">
<div class="required-fields">
<label>My Name:</label>
<input type="text" name="name" id="input" >
<p id="error" style="color:red"></p>
</div>
<input type="button" onclick="checkFields()" value="Send Message"/>
</form>
&#13;