下面的代码会在输入信息后显示和消失但是我希望错误消息一次显示一个,即使我有多个字段要验证。现在,点击按钮后会显示所有验证。
HTML:
<form>
<br>
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name" required> <span class="error" id="first_error"></span>
<label for="last_name">Last Name:</label>
<input type="text" id="last_name" name="last_name" required> <span class="error" id="last_error"></span>
jQuery的:
$(document).ready(function(){
$("#mysubmit").click(function(){
var myFirstName = $("#first_name").val().trim();
$("#first_name").val(myFirstName);
var myLastName = $("#last_name").val().trim();
$("#last_name").val(myLastName);
var myFirstNameError = $('#first_error').val();
$('#first_error').val("");
if(!myFirstName)
{
$("#first_error").html("You must Enter a First Name");
}
else
{
$("#first_error").html("");
}
if(!myLastName)
{
$("#last_error").html("You must Enter a Last Name");
}
else
{
$("#last_error").html("");
}
答案 0 :(得分:1)
我希望这会对你有所帮助。下一次使你的代码可读并发布完整的代码,没有任何语法错误,如括号关闭或手动错误,如无提交按钮等
$(document).ready(function(){
$("#mysubmit").click(function(){
var myFirstName = $("#first_name").val().trim().length;
// $("#first_name").val(myFirstName);
var myLastName = $("#last_name").val().trim().length;
// $("#last_name").val(myLastName);
//var myFirstNameError = $('#first_error').val();
//$('#first_error').val("");
if(myFirstName>0)
{
$("#first_error").html("");
}
else
{
$("#first_error").html("You must Enter a First Name");
}
if(myLastName>0 || !myFirstName>0)
{
$("#last_error").html("");
}
else
{
$("#last_error").html("You must Enter a Last Name");
}
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<br>
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name" required> <span class="error" id="first_error"></span><br>
<label for="last_name">Last Name:</label>
<input type="text" id="last_name" name="last_name" required> <span class="error" id="last_error"></span><br>
<button id="mysubmit" >Submit</button>
</form>
&#13;