css 取消选择其他单选按钮组上的单选按钮

k75qkfdt  于 2022-11-27  发布在  其他
关注(0)|答案(3)|浏览(260)

假设我有这样一个div:

<div>
    <div>   
        <input type="radio" id="cheque" name="type" value="" /> 
        <label for="cheque">Cheque</label>
    </div><br />
    <div>   
        <input type="radio" id="credit_card" name="type" value="" />    
        <label for="credit_card">Credit card</label>
        <div style="margin-left:45px;">
            <label for="visa">Visa</label>
            <input type="radio" id="visa" name="card_type" value="" /><br />

            <label for="mastercard">Mastercard</label>
            <input type="radio" id="mastercard" name="card_type" value="" />
        </div>
    </div>
</div>

here所示,用户可以选择“支票”或“信用卡”,但假设用户选择了“Visa”,然后返回再次选择“支票”,“Visa”单选按钮仍处于选中状态。我不希望出现这种情况。我希望在用户选择“Visa”或“Mastercard”,然后返回选择“支票”时,自动选择“信用卡(当选择了Visa或Mastercard时),我希望取消选中单选按钮“信用卡”、“Visa”和“Mastercard”。这可以只用html和css来完成吗?还是必须使用javascript来完成?
谢谢你

gcxthw6b

gcxthw6b1#

不幸的是,HTML中没有“子分组”。
检查the <input> element的定义:

属性

type
radio:单选按钮,必须使用value属性定义该项目提交的值,使用checked属性表示该项目是否默认选中,name属性值相同的单选按钮属于同一个**“单选按钮组”**;一次只能选择组中的一个单选按钮。
此外,如果您搜索页面,唯一与分组相关的位是<optgroup>,但它仅适用于<option>标签。
为此,您唯一的选择是使用JavaScript:

document.getElementById('mastercard').onclick = function () {
    document.getElementById('credit_card').checked = true;
};
document.getElementById('visa').onclick = function () {
    document.getElementById('credit_card').checked = true;
};
document.getElementById('cheque').onclick = function () {
    document.getElementById('mastercard').checked = false;
    document.getElementById('visa').checked = false;
};

Your fiddle, with this code.

bbmckpt7

bbmckpt72#

在Java Script中添加此项

function cheque_onclick() {

visa.checked = false;
mastercard.checked = false;

}

function visa_onclick() {
credit_card.checked = true;

}

function mastercard_onclick() {
credit_card.checked = true;

}
k97glaaz

k97glaaz3#

在每个单选元素上使用相同的“name”属性。例如:
这将显示两个选项组,默认情况下选择选项1,如果用户选择选项2,则自动取消选择选项1

<input type="radio" id="r1" name="r" checked="checked"><label for="r1">Option 1</label>
<input type="radio" id="r2" name="r"><label for="r2">Option 2</label><br>

相关问题