I have a form which is divided into parts seperated by divs eg:
<form>
<div>
Account Details
&l开发者_开发问答t;/div>
<div>
Personal Details
</div>
<div>
...etctec
</div>
</form>
I want that when someone highlights or focuses on any element within the divs the div in question is highlighted using css. Consider the fact that I have applied a number of handlers to certain input elements on this form.
You could try:
$('input').focus(
function(){
// adds the 'highlight' class to the parent
$(this).closest('div').addClass('highlight');
});
With:
$('input').blur(
function(){
// removes the 'highlight' class from the parent so only one highlight is ever visible.
$(this).closest('div').removeClass('highlight');
});
And define the highlight
class in CSS:
.highlight {
background-color: #ffa;
}
JS Fiddle demo, please note that, in the demo, I use fieldset
s rather than div
to wrap the various label
and input
elements, but otherwise it's exactly the same principle.
Updated the demo for increased prettiness: Revised JS Fiddle.
Edited in response to question from OP:
Thats great - however theres a little problem with this code i.e that if ever an input within a div loses focus the div is shown as unhighlighted. Is there a way so that a div remains focus until an input element in another div is focused upon which the parent of the focused div would then get highlighted
Yeah, assuming that I've understood you right, that's pretty easy:
$('input').focus(
function() {
$(this)
.closest('form')
.find('.highlight')
.removeClass('highlight');
$(this).closest('fieldset').addClass('highlight');
});
JS Fiddle demo.
$('form > div').delegate('input', 'focus', function() {
$(this).closest('div').addClass('active');
}).delegate('input', 'blur', function() {
$(this).closest('div').removeClass('active');
});
Demo: http://jsfiddle.net/ThiefMaster/fG8Au/
If you want to be sure that only the div right inside the form tag is highlighted, use $(this).closest('form > div')
.
Create a highlight class in your CSS and try the following jQuery:
$('input, select, textarea').focus (function ()
{
var elem = $(this), container = elem.parents ('div');
container.siblings ().removeClass ('highlight');
container.addClass ('highlight');
})
Try this:
.highlight{background:#ddd}
$('input').focus(function(){
$(this).parent().parent().find('div.highlight').removeClass('highlight');
$(this).parent().addClass('highlight');
});
精彩评论