选择“Option"Div隐藏/显示使用JQuery
Select "Option" Div Hide/Show using JQuery
我试图创建一个自动隐藏/显示功能,当有人选择一个选择元素上的某个"选项"。下面是我对"selector"的设置:
<li id="foli16" class="name notranslate">
<label class="desc" id="title16" for="Field16">
Repeat Pattern
<span id="req_16" class="req"></span>
</label>
<span class="left">
<select id="Field16" style="margin-left: 0px;" name="" class="field select">
<option value="" <?php echo $doc_selected; ?>>None</option>
<option value="" <?php echo $doc_selected; ?>>Daily</option>
<option value="" <?php echo $doc_selected; ?>>Weekly</option>
<option value="" <?php echo $doc_selected; ?>>Monthly</option>
<option value="" <?php echo $doc_selected; ?>>Yearly</option>
</select>
</span>
<p class="instruct" id="instruct16"><small>How often does this test occur?</small></p>
</li>
当有人选择"daily"选项时,我希望显示id为"daily"的div。如果他们选择了一个不同的,它需要关闭可见的,并显示新的选择。
我以前用点击按钮和单个切换做过这件事,但我不确定如何为这么大的切换写这个,特别是使用选择"选项"。我想我的选项也需要ID。
你有5个选项元素,如果你有5个目标元素,应该隐藏/显示根据所选择的选项,你可以添加一个类到你的目标元素,并使用eq
和index
方法:
var $targets = $('.theTargets');
$('#Field16').change(function(){
var i = $('option:selected', this).index();
$targets.hide().eq(i).show();
});
如果您想通过ID选择目标元素:
$(function(){
var $targets = $('.theTargets'); // If they have a common class name
$('#Field16').change(function(){
var id = this.value.toLowerCase();
$targets.hide().filter('#' + id).show();
})
})
您可以使用select字段的更改函数,并获取所选选项的ID。
<script>
$(document).ready(function() {
//This will fire when an option is selected from <select>
$("#Field16").change(function() {
//Add a class to all div's so you can hide previous ones
$(".whateveryourclassis").hide();
//Get the ID of the selected option
var selectedID = $(this).attr("id") + "div";
//Show the right div. (assuming the div you want has the same ID as option
//with "div" after it
$("#" + selectedID).show();
}
}
</script>
根据tymeJV的答案构建,
我会给每个div将被隐藏/显示一个类名,如showhide
,然后
$("#Field16").change(function() {
//Get the ID of the desired div
var selectedID = $(this).val();
$(".showhide").hide();
$("#" + selectedID).show();
}
你可以试试这样做。
您可以将select绑定到onchange事件并获取值,如
$('#Field16').bind('change',function(){
$('.box').hide(); // All the elements you want to hide on change.
$('#'+$(this).val()).show();
});
http://jsfiddle.net/XKLx8/你可以这样做:
$('select').on('change', function () {
$('li').hide()
$('#' + this.value).show();
});
正是你想要的: