jquery validate empty field
I have a question related to jquery. Basically I want to do a very simple thing. I have a text input field. On submit, I want to display error message if the field is empty. I have done this way:
errMsg = "Please write name";
$("div#errMsg").css("background-color", "red");
$("div#errMsg").html(errMsg);
and in the HTML:
<div id="errMsg"></div>
<strong>Name: </strong>
<input name="name" id="name" type="text" maxlength="255" size="50" />
It works fine, however there is a problem. When I leave the field empty and it displays the error 开发者_高级运维message, the error message does not go away without refreshing the page. I am trying to do it so that when there is error message, and i type something in the field, it automatically remove the error without refreshing the page. Any help would be much appreciated. Thanks.
$('#name').keyup(function() {
if ($(this).val()) {
$("div#errMsg").fadeOut(100);
}
});
Be sure to call show()
$("div#errMsg")
next time you display it.
Register a listener for the keypress event. Then you can re-validate the field every time the user types something in it. An alternative is to use the change event, which is only triggered when the user changes the field, and then switches the focus to something else.
精彩评论