Add class to group specific div on focus with jQuery
In the following code, I'm trying to make it so that when an input is selected (focused), that the formhead
div in the associated fieldset changes its background color, and on blur it changes back. I would like to do this by adding a class to that same div on focus, and having that class removed on blur. jQuery closest is the most similar in concept to what I'm trying to do, but isn't appropriate because it will only target parent divs. Is there something else that would target the nearest div with that class, without affecting the other classes in the other fieldsets? Or do I have to get much more specific and id the formheads, etc?
<fieldset>
<div class="formhead">Heading Title 1</div>
<div class="fieldleft">
<label for="specificinput">Input Title</label>
<input type="text" class="forminput" id="specificinput">
</div>
<div class="fieldleft">
<label for="specificinput">Input Title</label>
<input type="text" class="forminput" id="specificinput">
</div>
</div>
</fieldset>
<fieldset>
<div class="formhead">Heading Title 2</div>
<div class="fieldleft">
<label for="specificinput">Input Title</label>
<input type="text" class="forminput" id="specificinput">
</div>
<div class="fieldleft">
<label for="specificinput">Input Title</label>
<input type="text" class="forminput" id="specificinput">
</div>
</div>
</fieldset>
And the jQuery:
<script type="text/javascript">
$(document).ready(function() {
$('input').focus(function( ){
$(this).closest('.formhead').addClass('bluebg');
开发者_C百科 });
$('input').focus(function( ){
$(this).closest('.formhead').removeClass('bluebg');
});
});
</script>
You can get the input's .formhead
with this line:
$(this).closest('fieldset').find('.formhead').addClass('bluebg');
You can also write this as (actually the same, using context):
$('.formhead', $(this).closest('fieldset')).addClass('bluebg');
The easiest way I see for your code would be something like:
$('input.forminput').bind('focus blur', function () {
$(this).closest('fieldset').find('.formhead').toggleClass('bluebg');
});
jsFiddle Demo
This will assign the same handler for onfocus
and onblur
, which will just toggle the class of .formhead
.
- Multiple events with
.bind()
.toggleClass()
You can also match the parent <div>
element with class fieldleft
using closest(), then proceed to its formhead
sibling using prevAll():
$(document).ready(function() {
$("input:text").bind("focus blur", function() {
$(this).closest(".fieldleft").prevAll(".formhead").toggleClass("bluebg");
});
});
you can use .next()
精彩评论