【发布时间】:2013-04-10 22:35:18
【问题描述】:
我试图确保用户只能选择一个复选框,但看起来没有选中任何内容。我做错了什么?
<div class="formField rsform-block rsform-block-typprofilu">
<br>
<input name="form[typprofilu][]" type="checkbox" value="Montreal (Oceľ)" id="typprofilu0" checked="checked">
<label for="typprofilu0">Montreal (Oceľ)</label>
<input name="form[typprofilu][]" type="checkbox" value="Halifax (Oceľ)" id="typprofilu1">
<label for="typprofilu1">Halifax (Oceľ)</label>
<input name="form[typprofilu][]" type="checkbox" value="Calgary (Hliník)" id="typprofilu2">
<label for="typprofilu2">Calgary (Hliník)</label>
<input name="form[typprofilu][]" type="checkbox" value="Niagara (Hliník)" id="typprofilu3">
<label for="typprofilu3">Niagara (Hliník)</label>
<input name="form[typprofilu][]" type="checkbox" value="Hudson (Hliník)" id="typprofilu4">
<label for="typprofilu4">Hudson (Hliník)</label><br>
<span id="component781" class="formNoError">Invalid Input</span>
<br>
</div>
jQuery:
jQuery('.rsform-block-typprofilu input#typprofilu0[type="checkbox"]').attr('checked',true);
jQuery('body').on('click','.rsform-block-typprofilu input[name="form[typprofilu][]"]',function(){
jQuery('.rsform-block-typprofilu input[name="form[typprofilu][]"]').attr('checked', false);
var whatIsChecked = jQuery(this).attr('id');
//var isChecked = jQuery(this).is(':checked');
jQuery(this).attr('id',whatIsChecked).attr('checked',true);
});
已编辑:带有单选按钮的解决方案
<div class="formField rsform-block rsform-block-typprofilu">
<br>
<input name="form[typprofilu]" type="radio" value="Montreal (Oceľ)" id="typprofilu0" checked="checked"><label for="typprofilu0">Montreal (Oceľ)</label><input name="form[typprofilu]" type="radio" value="Halifax (Oceľ)" id="typprofilu1"><label for="typprofilu1">Halifax (Oceľ)</label><input name="form[typprofilu]" type="radio" value="Calgary (Hliník)" id="typprofilu2"><label for="typprofilu2">Calgary (Hliník)</label><input name="form[typprofilu]" type="radio" value="Niagara (Hliník)" id="typprofilu3"><label for="typprofilu3">Niagara (Hliník)</label><input name="form[typprofilu]" type="radio" value="Hudson (Hliník)" id="typprofilu4"><label for="typprofilu4">Hudson (Hliník)</label><br>
<span id="component782" class="formNoError">Invalid Input</span>
<br>
</div>
jQuery('.rsform-block-typprofilu input#typprofilu0[type="radio"]').attr('checked',true);
jQuery('body').on('click','.rsform-block-typprofilu input[name="form[typprofilu]"]',function(){ // ez a radiok kozul a valasztasom
jQuery('.rsform-block-typprofilu input[name="form[typprofilu]"]').attr('checked', false);
var whatIsChecked = jQuery(this).attr('id');
var isChecked = jQuery(this).is(':checked');
jQuery(this).attr('id',whatIsChecked).attr('checked',true);
});
它没有改变...选择的是第一个...但在 HTML 中它似乎改变了选中的属性。
【问题讨论】:
-
为什么不使用单选按钮?
-
您可以使用单选按钮切换复选框,这将立即解决您的问题,因为它们是硬连线的,只允许一个选择。
-
因为使用单选按钮,我无法在第二次点击时更改选择。
-
@lostika 请在下面查看我的答案以及您未选择问题的解决方案。
-
使用 prop() 后,radio 发生了变化,但在代码jsfiddle.net/lostika86/HfTGG 中没有'checked' 属性@