Reputation: 7653
What I am trying to achive here is to target a couple of divs to show or hide depanding on what the val is. In this case it doesn't work, when I have only one div target it works, but only for 1 of the to hide not two of them. I am not really sure if I can target multiple divs ?
$(document).ready(function (){
$("#state").change(function() {
// foo is the id of the other select box
if ($(this).val() == "twoChoices") {
$("#foo", "#foo1", "#foo2", "#foo3").show();
}else{
$("#foo", "#foo1", "#foo2", "#foo3").hide();
}
});
<div class="form-group">
<label for="Choice" class="col-sm-8 control-label">How many?</label>
<div class="col-sm-2">
<select id="state" class="form-control">
<option value="oneChoice">1</option>
<option value="twoChoices">2</option>
</select>
</div>
</div>
<div id="foo" class="form-group">
<label for="Choice" class="col-sm-8 control-label">First to be</label>
<div class="col-sm-3">
<select id="mixOrSingle" class="form-control">
<option value="mix">Mix</option>
<option value="single">Single</option>
</select>
</div>
</div>
<div id="foo2" class="form-group">
<label for="Choice" class="col-sm-8 control-label">Second to be</label>
<div class="col-sm-3">
<select id="mixOrSingle" class="form-control">
<option value="mix">Mix</option>
<option value="single">Single</option>
</select>
</div>
</div>
Upvotes: 1
Views: 380
Reputation: 5226
You might be better using classes too, to keep this cleaner and easier to maintain ?
Say html:
<div id="foo" class="form-group twoChoice"></div>
<div id="foo1" class="form-group twoChoice"></div>
<div id="foo2" class="form-group twoChoice"></div>
and JS
$("#state").change(function() {
$("."+$(this).val()).toggle();
/* or what ever logic */
});
Your current example makes no sense, as, whatever the value, it hides the same elements, but I guess that's just to show the problem. The key would be to target the class rather than all those chained id's.
Update, forgot to say. A nice convention too is to name those classes more verbose, so easier to see what is happening in 12 months time :)
eg
<div id="foo" class="form-group js-hiddenBy_twoChoice"></div>
<div id="foo1" class="form-group js-hiddenBy_twoChoice"></div>
<div id="foo2" class="form-group js-hiddenBy_twoChoice"></div>
JS
$("#state").change(function() {
$(".js-hiddenBy_"+$(this).val()).hide();
});
Upvotes: 0
Reputation: 67207
Its because, the way you have used the multiple-selector
is wrong.
Try,
$("#foo,#foo1,#foo2,#foo3").show();
Full code,
$(document).ready(function (){
$("#state").change(function() {
$("#foo,#foo1,#foo2,#foo3").toggle($(this).val() == "twoChoices");
});
});
Upvotes: 2