我有两个选择元素。 <select>
#1位于<table>
之前,而<select>
#2位于<select>
之下。除了类名之外,每个元素的内容和功能都是相同的。
<select>
#1中选择一个选项时,我需要从<select class="togglebuildprojecturn_top togglebuildprojecturn">
<option value="allbuildsprojects">All</option>
<option value="prsm-spe-00058">prsm-spe-00058</option>
<option value="buab-tes-00058">buab-tes-00058</option><option value="buab-exs-00058">buab-exs-00058</option>
<option value="nonspecific">Build / Project non-specific</option>
</select>
<!--some table here-->
<select class="togglebuildprojecturn_bottom togglebuildprojecturn">
<option value="allbuildsprojects">All</option>
<option value="prsm-spe-00058">prsm-spe-00058</option><option value="buab-tes-00058">buab-tes-00058</option>
<option value="buab-exs-00058">buab-exs-00058</option> <option value="nonspecific">Build / Project non-specific</option>
</select>
#2中选择相同的选项。注意:以下代码不反之亦然。
HTML:
$('.togglebuildprojecturn_top').on('change', function() {
//First attempt that I expected to work...
var selectedbuildprojecturn = $(this).val();
var togglematch = ".togglebuildprojecturn_bottom[value='" + selectedbuildprojecturn +"']"
alert(togglematch); //Just testing here (I know I should be using console logs :-)
$(togglematch).attr('selected', true);
//Testing for targeting without selector as variable...
$(".togglebuildprojecturn_bottom[value='prsm-spe-00058']").attr('selected', true);
});
$('.togglebuildprojecturn_bottom').on('change', function() {
//First attempt that I expected to work...
var selectedbuildprojecturn = $(this).val();
var togglematch = ".togglebuildprojecturn_top[value='" + selectedbuildprojecturn +"']"
alert(togglematch); //Just testing here (I know I should be using console logs :-)
$(togglematch).attr('selected', true);
});
jQuery的:
{{1}}
的jsfiddle:
为方便起见:http://jsfiddle.net/clarusdignus/rtY75/3/
为什么没有选择必要的选项?
答案 0 :(得分:2)
您可以使用class
对这些元素进行大规模简化,并将val()
设置为当前选定的值。
$('.togglebuildprojecturn').change(function() {
$('.togglebuildprojecturn').val($(this).val());
});