views:

63

answers:

4

I am trying to display some message in span. but it is not working.

<script type="text/javascript">
    $(document).ready(function(){
            /****************************First Name validation******************************/
        $("#txtFirstName").bind("focusout",function(){
                if($(this).val()=="" || $(this).val()=="First Name")
                    {
                    $(this).siblings("span[id*='error']").text("First Name Required");
                    $(this).val("First Name");
                    }   
            });

        $("#txtFirstName").bind("focusin",function(){
                if($(this).val()=="First Name")
                    {
                    $(this).siblings("span[id*='error']").show("slow").text("");
                    $(this).val("");                    
                    }   
            }); /********************End First Name validation*****************************/
    });

Here is my html code for above code

 <td><input id="txtFirstName" type="text" value="First Name" runat="server"/><span class="error"></span></td>
+6  A: 
$(this).siblings("span.error").text("First Name Required");
Ivo Sabev
+4  A: 

You have to use class instead of id:

$(this).siblings("span[class*='error']").text("First Name Required");

But if the full class name is always error you can just use span.error or even better, if the span comes always after the input, use .next():

$(this).next().text("First Name Required");
Felix Kling
The downvote is really unnecessary. Yes, I was partly wrong before but at the very beginning, there was indeed a `]` missing. And I corrected my answer. And those who downvote without comment are .... well there is nothing to say about this anymore.
Felix Kling
+1 to correct an injustice :)
Nick Craver
@Nick Craver: Hehe thank you... I upvoted you as well, maybe I should comment that ;) Btw the video you linked to in one of your comments was really interesting. Thank you!
Felix Kling
I do agree no downvote was required
Shantanu Gupta
A: 

For the span selector try: span.error

$(this).siblings("span.error").text("First Name Required");
Jon
+2  A: 

Ivo has it right, you need span.error for a selector in this case. As a side note though, you can simplify the code a bit overall with chaining and making use of the .focusin() and .focusout() shortcuts:

$(function(){
  $("#txtFirstName").focusin(function(){
      if($(this).val()=="First Name")
          $(this).val("").siblings("span.error").hide();
  }).focusout(function(){
      if($(this).val()=="" || $(this).val()=="First Name")
         $(this).val("First Name").siblings("span.error")
                .text("First Name Required").fadeIn();
  });
});
Nick Craver
+1 for code improvements :)
Felix Kling