我有一组三个选项框,我试图保持禁用状态,直到选择了上一个框。我正在尝试使用onchange
事件触发一些脚本,该脚本启用以下框并填充选项但由于某种原因无法使其工作? #nap2
是第一个组合框,#nap4
如下。代码在click
事件上正常工作,但我需要在用户选择了一个选项后才能执行....
HTML
<select id="nap2" class="napkeeComponent napkeeCombobox">
<option>Rider 1</option>
<option>Rider 2</option>
<option>Rider 3</option>
<option>Rider 4</option>
<option>Rider 5</option>
</select>
<select id="nap4" class="napkeeComponent napkeeCombobox" disabled>
<option>Bike1</option>
<option>Bike2</option>
<option>Bike3</option>
<option>Bike4</option>
<option>Bike5</option>
</select>
JS
$(document).ready(function(){
$("#nap2").onchange(function(event){
var element = document.getElementById("nap2");
var selected = element.options[element.selectedIndex].text;
if(selected == "Rider 1"){
$('#nap4').removeAttr('disabled');
}
else{
if((selected == "Rider 2")){
$('#nap4').removeAttr('disabled');
}
}
event.stopPropagation();
event.preventDefault();
});
});
答案 0 :(得分:0)
没有onchange
事件,而是.on('change'
或.change
。所以使用以下任何一个:
$("#nap2").on('change',function(event){
var element = document.getElementById("nap2");
var selected = element.options[element.selectedIndex].text;
if(selected == "Rider 1"){
$('#nap4').removeAttr('disabled');
}
else{
if((selected == "Rider 2")){
$('#nap4').removeAttr('disabled');
}
}
event.stopPropagation();
event.preventDefault();
});
<强> DEMO 强>
更简化的版本:
$("#nap2").on('change',function(event){
var selected = $(this).find('option:selected').text() //get selected text
if(selected == "Rider 1" || selected =="Rider 2"){ //have a single condition with or
$('#nap4').removeAttr('disabled');
}
else
$('#nap4').attr('disabled',true); //In case you want to disable it again if different option is selected
});
<强> DEMO + 强>