Reputation: 28354
I have something like the following:
<div id="div1" style="display: block;">
text
</div>
<div id="div2" style="display: none;">
text
</div>
<div id="div3" style="display: none;">
text
</div>
When a certain event happens, I want to hide all but one div. So, for instance, I might want to show div2, while hiding div1 and div3. The problem is that the number of divs is arbitrary, so I can't simply go:
$("#div1").css("display", "none");
$("#div2").css("display", "block");
$("#div3").css("display", "none");
Because there might be one div or there might be four.
How can I do this with jQuery?
Upvotes: 1
Views: 345
Reputation: 3302
You may do it this way, on your event function:
function(){
$('#div' + $(this).val()).show().siblings('div').hide();
}
Upvotes: 0
Reputation: 160833
Give them a common class, for example, use for the click event:
$('.foo').click(function() {
$('.foo').not(this).hide();
});
Upvotes: 2
Reputation: 104775
First, lets add a class to your divs
<div id="div1" class="someDiv" style="display: block;">
text
</div>
<div id="div2" class="someDiv" style="display: none;">
text
</div>
<div id="div3" class="someDiv" style="display: none;">
text
</div>
Assuming your numbers are in a list:
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
And the jQuery
$("ul li").click(function() {
var divNum = $(this).text();
$(".someDiv").hide();
$("#div" + divNum).show();
});
Upvotes: 3
Reputation: 68576
I wasn't really sure what kind of event you wanted or if you'd allow us to use classes, so I went with change()
:
jQuery:
$('select').change(function(){
$('div').hide();
$('div#' + this.value).show();
});
HTML:
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<div id="1">1</div>
<div id="2">2</div>
<div id="3">3</div>
Upvotes: 3
Reputation: 10719
you're looking into jQuery selectors.. you can use wildcards, select multiple elements, first and last and much more..
$("#div1, $div2") (selects multiple divs)
$("$divX > first) (all elements with the same id, gets the first)
$("[id^=div]") (get's all elements starting with id div)
http://www.w3schools.com/jquery/jquery_ref_selectors.asp
Upvotes: 1