David
David

Reputation: 5537

Prev not working inside div

I am trying to change the colour of my label when the texbox has focus

 <div class="editor-label">
     <%: Html.LabelFor(model => model.FirstName) %>
 </div>
 <div class="editor-field">
     <%: Html.TextBoxFor(model => model.FirstName) %>
     <%: Html.ValidationMessageFor(model => model.FirstName) %>
 </div>

This is my javascript

  $(':text').focus(function () {
        $(this).prevAll("label").last.css("color", "blue");
  });

$(this).prevAll() is always empty. But $(this).next() and $(this).nextAll() has a span

Please help I would really appreciate any assistance

Upvotes: 0

Views: 278

Answers (4)

David
David

Reputation: 5537

This is what I did

 <script type="text/javascript">
        $(':text').focus(function () {
            $(this).closest('div').prev().children('label').addClass("selected");
        });

        $(':text').blur(function () {
            $(this).closest('div').prev().children('label').removeClass("selected")
        });

 </script>

please let me know what you think.

Upvotes: 1

Naveed Ahmad
Naveed Ahmad

Reputation: 3175

You can do something like this as per my understanding:

$('div.editor-field input').focus(function () {
    $('div.editor-label label').css({"color":"black"});//Reset color for all labels
    $(this).parent().prev().find('label').css({"color":"blue"});
});

Upvotes: 1

Sang Suantak
Sang Suantak

Reputation: 5265

$(this).prevAll("label") is empty because prevAll("label") will look for label siblings of the text box. You should do something like this instead:

$(':text').focus(function () {
    $(this).parent("div").prev().find("label").css("color", "blue");
});

next() and nextAll() is returning a span because the following code will be rendered as a span, which is the next element after the textbox.

<%: Html.ValidationMessageFor(model => model.FirstName) %>

Upvotes: 2

chrisp_68
chrisp_68

Reputation: 1781

You could try finding it using the jQuery attr instead something like :

$('label[for="FirstName"]').css("color", "blue"); 

(not tested, sorry!)

Upvotes: 1

Related Questions