I have the following html structure
<div id="container">
<div class="label">
@Html.LabelFor(m => m.SomeProperty)
</div>
<div class="input">
@Html.EditorFor(m => m.SomeProperty)
</div>
<!--on and on-->
</div>
What I want to do is set a background-color on the label div, when the input in the corresponding div has focus.
In other words, when the user clicks on (or tabs to) the textbox for SomeProperty, I want to highlight the label for SomeProperty by adding a css class to the labels div.
I know I can set class=”SomeProperty” on the label div and then have some jQuery to add some css like this:
$('#container input').focus(function () {
var thisId = $(this).attr('id');
$('.' + thisId).addClass('highlight');
//...
});
But I’m wondering if there is a better way. I don’t really want to assign classes to all the label div’s as it seems sloppy and maybe hard to maintain down the road.
The way I see it, I want to write a script that can jump up one level, and then grab the previous sibling, probably some combination of parent() and prev(), but I’ve not been able to get it right. Any suggestions?
I’d suggest, if the
.labelelement will always precede the.inputelement:Or, to allow a more flexible DOM-independent approach: