我有一个选择输入:
<select size="1" name="filter" style="width:90px;" id="priority_filter" onchange="filter_user_trainings();">
<option value="all">All</option>
<option value="optional">Optional</option>
<option value="mandatory">Mandatory</option>
<option value="essential">Essential</option>
<option value="custom">Custom</option>
</select>
<div style="width: 50%; text-align: right; float: right">
<input type="checkbox" id="opt_box" onchange="somestuff()">Optional
<input type="checkbox" id="mand_box" onchange="somestuff()" checked="checked">Mandatory
<input type="checkbox" id="ess_box" onchange="somestuff()">Essential
</div>
和一个jQuery代码:
switch(priority_filter){
case 'all':
$("#opt_box").attr({checked: "checked"});
$("#mand_box").attr({checked: "checked"});
$("#ess_box").attr({checked: "checked"});
break;
case 'optional' :
$("#opt_box").attr({checked: "checked"});
$("#mand_box").removeAttr("checked");
$("#ess_box").removeAttr("checked");
break;
case 'essential' :
$("#ess_box").attr({checked: "checked"});
$("#mand_box").removeAttr("checked");
$("#opt_box").removeAttr("checked");
break;
case 'mandatory' :
$("#mand_box").attr({checked: "checked"});
$("#opt_box").removeAttr("checked");
$("#ess_box").removeAttr("checked");
case 'custom' :
$("#mand_box").attr({checked: "checked"});
$("#opt_box").removeAttr("checked");
$("#ess_box").removeAttr("checked");
break;
}
我想在"onchange"属性中调用该函数。当js切换复选框的值,但它不工作。我该怎么修理它?
试试这个
<select size="1" name="filter" style="width:90px;" id="priority_filter" onchange="filter_user_trainings(this);">
JS
function filter_user_trainings(obj){
var priority_filter=$(obj).val();
switch(priority_filter){
case 'all':
$("#opt_box").attr({checked: "checked"});
$("#mand_box").attr({checked: "checked"});
$("#ess_box").attr({checked: "checked"});
break;
case 'optional' :
$("#opt_box").attr({checked: "checked"});
$("#mand_box").removeAttr("checked");
$("#ess_box").removeAttr("checked");
break;
case 'essential' :
$("#ess_box").attr({checked: "checked"});
$("#mand_box").removeAttr("checked");
$("#opt_box").removeAttr("checked");
break;
case 'mandatory' :
$("#mand_box").attr({checked: "checked"});
$("#opt_box").removeAttr("checked");
$("#ess_box").removeAttr("checked");
case 'custom' :
$("#mand_box").attr({checked: "checked"});
$("#opt_box").removeAttr("checked");
$("#ess_box").removeAttr("checked");
break;
}
}
我觉得应该是$("#opt_box").attr("checked", "checked")
;而不是$("#opt_box").attr({checked: "checked"});
。看看是不是这样。
还需要将参数传递给方法onchange="filter_user_trainings(<put selected option from dropdown here>);"
$("#opt_box").on('click',function(){
if($(this).is(':checked')){
// do your work here
}
});
看看这个小提琴。我稍微重构了一下你的代码,但那不是最重要的部分。
- 你应该修改"checked" 属性而不是属性
- 你必须自己触发change事件,因为在通过JS设置属性或属性时不会触发。
因此,您必须触发目标复选框上的更改事件,并在之后,将属性重新设置为所需的值(就像在我的fiddle中一样),因为触发更改事件自然也会更改复选框的状态。
$checkboxes.prop('checked', true).trigger('change');
Update: Ok,似乎触发JS的变化实际上不会改变复选框的属性,所以你可以在值被设置后触发一个变化,并获得正确的值(这是当前状态)。更新了我的小提琴