Reputation: 15
Okay so the code shown here at http://jsfiddle.net/PayBt/ works perfectly but I have one problem. My values CAN'T be numbers which kills the code.
HTML:
<select id="additional" name="additional" value="{{course}}">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="apatient6">6</option>
</select>
<div id="workshop1" class="formbox">stuff</div>
<div id="workshop2" class="formbox">stuff</div>
<div id="workshop3" class="formbox">stuff</div>
<div id="workshop4" class="formbox">stuff</div>
JS.
$(document).ready(function () {
$('.formbox').hide();
$('#additional').change(function () {
$('.formbox').hide();
for (i = 1; i <= $(this).val(); i++) {
$('#workshop' + i).show();
}
});
});
The options I see are make it $('#workshop' + val).show(); instead of $('#workshop' + i).show();. Or find a way to call the div's by the selectors ID's.
Basically how to show / hide multiple divs with out using numerical values?
Thanks for any help!
Upvotes: 1
Views: 176
Reputation: 1434
Assuming you are interested in the selected index of the element, a simple tweak to your existing could is sufficient!
$(document).ready(function () {
$('.formbox').hide();
$('#additional').change(function () {
$('.formbox').hide();
//jquery api magic
iters = $("#additional").get(0).selectedIndex;
for (i = 1; i <= iters; i++) {
$('#workshop' + i).show();
}
});
});
Upvotes: 0
Reputation: 364
You can grab the selectedIndex from the DOM-element, which is what it sounds like. The index of the selected item. Then you can use the :lt() selector in jQuery to grab all elements with a lower index:
$('#additional').change(function () {
$('.formbox').hide();
var selectedIndex = $('#additional').get(0).selectedIndex;
$('.formbox:lt(' + selectedIndex + ')').show();
});
http://api.jquery.com/lt-selector/
Example: http://jsfiddle.net/PayBt/10/
Upvotes: 1
Reputation: 44740
You can add custom data attribute like data-value
like this -
Html : (same for other options)
<option data-value='6' value="apatient6">6</option>
Js :
$(document).ready(function () {
$('.formbox').hide();
$('#additional').change(function () {
$('.formbox').hide();
for (i = 1; i <= parseInt($('option:selected',this).data('value')); i++) {
$('#workshop' + i).show();
}
});
});
Demo -->
http://jsfiddle.net/PayBt/8/
Upvotes: 2