如何一次只选择一个单选按钮,并在数据来自数据库时在javascript中取消选择其他单选按钮
How to select only one radio button at one time and deselect the others in javascript when the data are comes from database?
可以选择所有单选按钮。但我想允许用户只选择一个单选按钮。
这是 HTML 代码。
$jsqla = mysql_query("select * from products where id='$product_id'") or die(mysql_error());
$jfeta = mysql_fetch_assoc($jsqla);
$formats = explode(";", $jfeta['formats']);
<div class="">
<?php foreach($formats as $v){ ?>
<label style="line-height: 1.25em;display: block;width: 100px;margin-right: 10px;float: left;">
<div id="format-id_<?php echo $v?>" style="border: 1px solid;border-radius: 9px;text-align: center;padding-top: 10px;padding-bottom:10px;padding-left: 3px;padding-right: 3px;border-color: #cccccc;font-family: 'SSemibold'; font-size: 13px; color: #44b7da;">
<input type="radio" value="<?php echo $v; ?>" name="abc" style="visibility:hidden;" id="<?php echo $v ?>" onClick="changeColour(this)"/>
<span style="margin:-17px auto auto 0px;display:block;"><?php echo $v; ?></span>
</div>
</label>
<?php } ?>
</div>
这是JavaScript代码。
<script type="text/javascript">
function changeColour(raid) {
var raid1 = raid.id;
document.getElementById("format-id_"+raid1).style.backgroundColor = "#cccccc";
}
</script>
$(document).ready(function(e) {
$(':radio').bind('change',function(){
var th = $(this), id = th.attr('id');
//alert(th);
if(th.is(':checked')){
$(':radio[id="' + id + '"]').not($(this)).attr('disabled',true);
}
else
{
$(':radio[id="' + id + '"]').not($(this)).attr('disabled',false);
}
});
});
演示
如果我理解您的问题(也许我不理解),您希望用户选择一个单选按钮,然后禁用组中的所有其他按钮。如果是这种情况,下面就可以完成了这项工作。
它获取所有具有相同名称的单选按钮,并禁用未选中的单选按钮:
function changeColour(raid) {
var button, buttons = document.getElementsByName(raid.name);
for (var i=0, iLen=buttons.length; i<iLen; i++) {
button = buttons[i];
if (!button.checked) {
button.disabled = true;
button.style.backgroundColor = "#cccccc";
}
}
}
如果您只想禁用它们,则:
function changeColour(raid) {
var buttons = document.getElementsByName(raid.name);
for (var i=0, iLen=buttons.length; i<iLen; i++) {
buttons[i].disabled = !buttons[i].checked;
}
}
我不知道为什么,但它是因为你的div 而发生的
<div id="format-id" .......>
尝试这样的事情:
<div>
<?php for($i=0;$i<10;$i++){ ?>
<input type="radio" value="<?php echo $i; ?>" name="abc" id="<?php echo $i ?>" onClick="javascript:changeColour(this)"/>
<span style="margin:-2px auto auto 0px;display:block;"><?php echo $i; ?></span>
<?php } ?>
</div>
我不确定我是否正确理解,但您可以轻松地在每个单选按钮上执行以下操作。这样只能激活一个按钮。也就是说,如果您使用的是引导程序。
<input type="radio" data-toggle="button" >
带工作小提琴:http://jsfiddle.net/8xrhr93g/
相关文章:
- 根据页面加载时的单选按钮选择显示某些字段
- Ng点击记住单选按钮选择
- Angular未更新单选按钮选择
- 阅读JS中的单选按钮选择
- JQuery IE11 单选按钮选择器
- 确认单选按钮选择
- 贝宝表单问题的单选按钮选择
- 使用javascript在单选按钮选择上加载URL
- 显示基于多个单选按钮选择的图像
- 基于输入值的单选按钮选择
- 将域类id返回到由单选按钮选择的控制器
- 无法更改单选按钮选择 - KnockoutJS
- 单选按钮选择列表框更改并将 NULL 值传递给每个列表框
- 用户在Javascript的帮助下,仅通过单选按钮选择一个付款方式(信用卡)
- 基于多个单选按钮选择显示或隐藏元素
- 如何根据单选按钮选择在表中切换多个输入
- 无法更改单选按钮选择
- 提交页面而不为所需单选按钮选择值
- 使用基于单选按钮选择的 jquery 将表格单元格添加到行尾
- j查询动态验证单选按钮选择