我希望当我专注于文本框时,如果它是空的,则应显示“名称是必需的”,如果我们输入一个字母,则该消息(“名称是必需的”)应该消失。
$("#name").focus(function() {
var name = $("#name").val();
if (name != "") {
$("#name-error").text("");
} else {
$("#name-error").text("Name is required.");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is a text box in form for name in a form
<label>My Name:</label>
<input type="text" id="name" />
<span id="name-error">*</span>
答案 0 :(得分:1)
使用.keyup
事件处理程序
$("#name").on('keyup focus',function() {
var name = $("#name").val();
if (name != "") {
$("#name-error").text("");
} else {
$("#name-error").text("Name is required.");
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>My Name:</label>
<input type="text" id="name" />
<span id="name-error">*</span>
&#13;