我正在使用以下HTML和JS与bootstrap-switch.org来切换表单中的单选按钮组。但是,在激活/显示其组时,我无法在第二组中第一个单选按钮被默认“检查”。
HTML
<div class="form-group">
<label class="col-sm-3 control-label">Form Group</label>
<div class="col-sm-6">
<!-- Bootstrap switch checkbox -->
<div class="switch">
<input id="optswitch" type="checkbox" name="opt_switch" data-on-color="primary" data-off-color="info" data-on-text="Group 1" data-off-text="Group 2" checked>
</div>
<!-- /Bootstrap switch checkbox -->
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="keysize">Form Options</label>
<div class="col-sm-8">
<div class="gp1">
<label class="radio-inline custom-radio">
<input type="radio" name="keysize" data-label="2048bit" id="keysize1" value="2048" checked>
</label>
<label class="radio-inline custom-radio">
<input type="radio" name="keysize" data-label="3072bit" id="keysize2" value="3072" >
</label>
<label class="radio-inline custom-radio">
<input type="radio" name="keysize" data-label="4096bit" id="keysize3" value="4096" >
</label>
</div>
<div class="gp2" style="display:none">
<label class="radio-inline custom-radio">
<input type="radio" name="keysize" data-label="256bit" id="keysize4" value="256">
</label>
<label class="radio-inline custom-radio">
<input type="radio" name="keysize" data-label="384bit" id="keysize5" value="384" >
</label>
</div>
</div>
</div>
JS (使用JQuery 1.10.2)
$(document).ready(function() {
$("[name='opt_switch']").bootstrapSwitch();
$('#optswitch').on('switchChange', function (e, data) {
var $el = $(data.el),
value = data.value;
if(value){//this is true if the switch is on
$('.gp1').show();
$('.gp2').hide();
$('#keysize1').prop('checked', true);
}else{
$('.gp2').show();
$('.gp1').hide();
$('#keysize4').prop('checked', true);
}
});
});
它似乎适用于此fiddle。但不是在我的环境中。 但我无法弄清楚为什么。有什么想法吗?
更新 我也在使用prettyCheckable,但我猜这不应该影响交换机的行为?
更新2
看起来这是prettyCheckable的问题。这个fiddle显示了这个问题。仍然无法理解为什么prettyCheckable它没有使用.prop('checked', true);
答案 0 :(得分:0)
这是prettyCheckable的一个问题。通过.prop('checked', true)
进行的无线电更改确实发生了,prettyCheckable只是没有反映它。
该插件确实有'Check/Uncheck' method,但我无法让它工作。
在.next('a').addClass('checked');
解决问题后添加.next('a').removeClass('checked');
或.prop('checked', true/false)
:
$(document).ready(function() {
$('.custom-checkbox input, .custom-radio input').prettyCheckable();
$("[name='opt_switch']").bootstrapSwitch();
$('#optswitch').on('switchChange', function (e, data) {
var $el = $(data.el),
value = data.value;
if(value){//this is true if the switch is on
$('.gp1').show();
$('.gp2').hide();
$('#keysize4').next('a').removeClass('checked');
$('#keysize5').next('a').removeClass('checked');
$('#keysize1').prop('checked', true).next('a').addClass('checked');
}else{
$('.gp2').show();
$('.gp1').hide();
$('#keysize1').next('a').removeClass('checked');
$('#keysize2').next('a').removeClass('checked');
$('#keysize3').next('a').removeClass('checked');
$('#keysize4').prop('checked', true).next('a').addClass('checked');
}
});
});
以上作品(fiddle),但我不确定这是最佳解决方案。