1

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!

4

3 回答 3

2

您可以像这样添加自定义数据属性data-value-

Html:(其他选项相同

<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();
        }
    });
});

演示 --> http://jsfiddle.net/PayBt/8/

于 2013-06-18T15:14:01.190 回答
1

您可以从 DOM 元素中获取 selectedIndex,这就是它听起来的样子。所选项目的索引。然后你可以在 jQuery 中使用 :lt() 选择器来抓取所有具有较低索引的元素:

$('#additional').change(function () {
    $('.formbox').hide();
    var selectedIndex = $('#additional').get(0).selectedIndex;
    $('.formbox:lt(' + selectedIndex + ')').show();
});

http://api.jquery.com/lt-selector/

示例:http: //jsfiddle.net/PayBt/10/

于 2013-06-18T15:25:03.540 回答
0

假设您对元素的选定索引感兴趣,对现有可能的简单调整就足够了!

$(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();
        }
    });
});
于 2013-06-18T15:32:05.110 回答