我是JavaScript新手。我知道如何创建一个警告框,如果一个字段在HTML表单中保留为空,现在创建一条错误消息,但有人可以告诉我如果多个字段为空,如何显示多个错误消息?下面是我的表单和JavaScript的HTML代码:
<form action="form.php" method="post" name="contactform"
onsubmit="return validateForm()">
<fieldset>
<legend>Your Details:</legend>
<label for="name">Name:</label><br>
<input type="text" name="name" id="name" onblur="validateForm()"><br>
<span id="error"></span>
<label for="email">Email:</label><br>
<input type="text" name="email" id="email"><br>
<label for="telephone">Telephone:</label><br>
<input type="text" name="telephone" id="telephone">
</fieldset>
<br>
<fieldset>
<legend>Your Information:</legend>
<p>
<label for="service">What service are you inquiring about?</label>
<select name="service" id="service">
<option value="Collision">Collision</option>
<option value="Mechanical">Mechanical</option>
<option value="Custom">Custom</option>
<option value="Other">Other</option>
</select>
</p>
<label for="comments">Comments:</label>
<br>
<textarea name="comments" id="comments" rows="4" cols="40">
</textarea><br>
<input type="submit" value="Submit"/>
</fieldset>
<script src="validate.test.js"></script>
</form>
function validateForm()
{
var name = document.forms["contactform"]["name"].value;
if (name == "")
{
document.getElementById('error').innerHTML="Please enter your name";
return false;
}
}
答案 0 :(得分:0)
您需要通过脚本代码包围JavaScript代码。
<script type="text/javascript">
function validateForm()
{
var name = document.forms["contactform"]["name"].value;
if (name == "")
{
document.getElementById('error').innerHTML="Please enter your
name";
return false;
}
}
</script>
答案 1 :(得分:0)
required
HTML元素上使用input
属性。
它指定在提交表单之前必须填写输入字段。
<form action="form.php" method="post" name="contactform"
onsubmit="return validateForm()">
<fieldset>
<legend>Your Details:</legend>
<label for="name">Name:</label><br>
<input type="text" name="name" id="name" required><br>
<span id="error"></span>
<label for="email">Email:</label><br>
<input type="text" name="email" id="email" required><br>
<label for="telephone" required>Telephone:</label><br>
<input type="text" name="telephone" id="telephone" required>
<input type="submit">
</fieldset>
答案 2 :(得分:0)