Shantanu Gupta
Shantanu Gupta

Reputation: 21188

Why my jquery is not working for a span tag

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>

Upvotes: 1

Views: 198

Answers (4)

Felix Kling
Felix Kling

Reputation: 816312

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");

Upvotes: 4

Nick Craver
Nick Craver

Reputation: 630369

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();
  });
});

Upvotes: 3

Jon
Jon

Reputation: 6046

For the span selector try: span.error

$(this).siblings("span.error").text("First Name Required");

Upvotes: 0

Ivo Sabev
Ivo Sabev

Reputation: 5230

$(this).siblings("span.error").text("First Name Required");

Upvotes: 6

Related Questions