Reputation: 2592
In my program I have several very similar drop-down menus all with the same name (foo in the following example). On change they hide or show a nearby div tag depending on whether or not "ON" was selected.
$('.togClass').hide();
$('[name*="foo"]').change(function(){
if ($('[value="ON"]').is(':selected')) {
$('.togClass').show('blind', 1000);
} else {
$('.togClass').hide(1000);
}
});
As it is, all of the div tags with class "togClass" toggle when any of the drop down menus choose "ON", is there a way that I can choose to show/hide only the nearby div to the drop-down that chooses "ON"(they are nested in the same div)? I don't want to write a copy of this function for every div I want to hide.
Here is how it works in the HTML:
<select name="foo">
<option value="OFF">OFF</option>
<option value="ON">ON</option>
</select><br/>
<div class="togClass">
//Stuff
</div>
Upvotes: 2
Views: 312
Reputation: 17762
Ofcourse you can. Check out the jquery doc about traversing: http://api.jquery.com/category/traversing/ It has a lot of great examples.
For your problem the solution could be: .closest()
$('div.togClass').hide();
$('select[name*="foo"]').change(function(){
if ($(this).val() == "ON") {
$(this).siblings('div.togClass').show('blind', 1000);
} else {
$(this).siblings('div.togClass').hide(1000);
}
});
Upvotes: 3
Reputation: 23943
You have to tell us a bit more about what "nearby" means. But it appears that the fundamental piece you're missing is the use of $(this)
within the change
function. Instead of identifying any .togClass
item, you want to identify a specific one relative to $(this)
-- the element being changed.
Here's one way to do it with the assumption that the associated .togClass
div is the next one to be found in the DOM.
$('[name*="foo"]').change(function(){
if( $(this).is(':selected') ) { // relative to the selected item
$(this).next('.togClass').show('blind',1000);
} else {
$(this).next('.togClass').hide(1000);
}
});
Where you see .next()
you'll actually need the appropriate jQuery traversal methods -- unlikely to be the one I've randomly assumed in the example.
Upvotes: 1