0

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.

Mostafa Elkady
  • 5,645
  • 10
  • 45
  • 69

4 Answers4

1

You prevent submit by returning false. E.g.

if($('#name').val().trim() == "")
{
    Alert('Please write name');
    return false;
}
peterthegreat
  • 406
  • 3
  • 9
0

In the input textbox, you will want to detect changes to the text:

$("#name").onChange( function(event){ //Re-evaluate to see if error should be displayed} );
Brian Liang
  • 7,734
  • 10
  • 57
  • 72
  • The change event is sent to an element when its value changes. This event is limited to elements, – Erik Philips Nov 29 '10 at 07:57
  • This will not fulfil the requirement: i type something in the field, it automatically remove the error without refreshing the page. – Erik Philips Nov 29 '10 at 07:59
0

Check out jquery how to detect a textboxs content has changed.

Community
  • 1
  • 1
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
0

You can attach a handler when the page first loads to the #name element's change event like this:

$("#name").change(function() {
  //with .toggle(bool) we're only showing the element if the value's empty
  $("#errMsg").toggle(this.value == "").html("Please write name");
}).change(); //call it initially, in case we started invalid

This also involves giving the <div> CSS for styling, which is easier to maintain:

#errMsg { background-color: red; } /*could also use a class and apply that here*/

In your submit() handler there's no need (unless you change the value programmatically), but if you feel the need to run the check again, just call .change() to execute the handler again, like this:

$("#name").change();
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155