我是JQuery的新手,我想问的是如何选择一个选项,然后自动选择另一个具有第一选项属性的选项。
我已经给出了这样的代码:
<select name="kendaraan">
<option value="" selected>pilih kendaraan!</option>
<option value="B 2011 DR" class="B2011DR">B 2011 DR</option>
<option value="R 3333 OKI" class="R3333OKI">R 3333 OKI</option>
<option value="k03">jazz</option>
<option value="k04">innova</option>
</select>
<select name="driver">
<option value="" selected>pilih kendaraan!</option>
<option value="s02" car="B2011DR" style="display:none">jojon</option>
<option value="s01" car="B2011DR" style="display:none">mamat</option>
<option value="s04" car="R3333OKI" style="display:none">tukul</option>
<option value="s03" car="R3333OKI" style="display:none">mamat</option>
<option value="s07" car="k03" style="display:none">bejo</option>
<option value="s05" car="k03" style="display:none">mamat</option>
<option value="s06" car="k03" style="display:none">tukul</option>
<option value="s08" car="k04" style="display:none">budi</option>
<option value="s09" car="">komeng</option>
</select>
$('select[name=kendaraan]').change(function() {
//hide all option
$('select[name=driver] option').css('display','none');
//display option only for matched driver
var isCar = $('select[name=driver] option[car='+$(this).val()+']');
isCar.css('display','block');
//auto select first matched diriver
$('select[name=driver]').val( $(isCar[0]).val() )
})
但jquery代码用于获取“kendaraan”的值,如何将其与类匹配,而不是值?
答案 0 :(得分:1)
我认为这正是你想要的。试试以下
<script>
// make a function that will perform your desired task every time when dropdwon value changes.
// so call this function in document.ready and also bind change event of dropdown to this function
$(function () {
onDDLchange();
$('select[name$=kendaraan]').change(function () {
onDDLchange();
});
});
function onDDLchange() {
var j = 0;
var v = $('select[name$=kendaraan]').val();
$('select[name$=driver] option').hide();
$('select[name$=driver] option').each(function (i) {
if (v == $(this).attr('car')) {
if (j == 0) {
$(this).attr('selected', 'selected');
j = j + 1;
}
$(this).show();
}
});
}
</script>
答案 1 :(得分:0)
$(function() { // document ready
$('option[value=""]').attr('selected', 'selected');
});
自动选择第一个选项