如何取消选择单选按钮并在单击时重新选择默认按钮?

时间:2019-01-07 11:36:13

标签: javascript html radio-button

基本上我想有三个单选按钮。默认情况下,第一个被选中。单击第二个,它将变为选中状态。但是,如果再次单击第二个,则在选择第二个之后,我希望它重新选择第一个。第二个行为同样适用于第三个行为。

感谢您的帮助! ^ _ ^

4 个答案:

答案 0 :(得分:0)

您可以使用css选择单选按钮,并在那里执行任何样式

input[type="radio"]:checked+label { font-weight: bold; }
<input id="rad1" type="radio" name="rad"/><label for="rad1">Radio 1</label>
<input id="rad2" type="radio" name="rad"/><label for="rad2">Radio 2</label>
<input id="rad3" type="radio" name="rad"/><label for="rad3">Radio 3</label>

答案 1 :(得分:0)

使用下面的代码来满足您的要求。

function CheckDefault()
{
if(this.checked){ document.getElementById('rad1').checked=true;}
}


<input id="rad1" type="radio" name="rad"/><label for="rad1">Radio 1</label>
<input id="rad2" type="radio" name="rad" onclick="CheckDefault()"/><label for="rad2">Radio 2</label>
<input id="rad3" type="radio" name="rad" onclick="CheckDefault()"/><label for="rad3">Radio 3</label>

答案 2 :(得分:0)

我已使用单选按钮onclick事件功能逻辑来获得所需的功能:

<p>Select your choice:</p>
<div>
    <input type="radio" id="choice1" name="val" value="1" onclick="app(this.value)">
    <label for="choice1">First</label>
    <input type="radio" id="choice2" name="val" value="2" onclick="app(this.value)">
    <label for="choice2">Second</label>
    <input type="radio" id="choice3" name="val" value="3" onclick="app(this.value)">
    <label for="choice3">Third</label>
</div>
<script src="app.js"></script>


app.js

var radio2Counter = 0;
var radio3Counter = 0;

function app(selectedVal) {

    switch(selectedVal) {
        case '2':
            radio3Counter = 0;
            if (++radio2Counter == 2) {
                document.getElementById('choice1').checked = true;
                radio2Counter = 0;
            }
            break;
        case '3':
            radio2Counter = 0;
            if (++radio3Counter == 2) {
                document.getElementById('choice1').checked = true;
                radio3Counter = 0;
            }
            break;
        default:
            // console.log('Radio 1');
    }
}

答案 3 :(得分:0)

here is my solution (no metter how many checkboxes do you use, this code will work):

js:

var curr = '';
var prev = '';

$('input').on('click', function(){

  if( curr == $(this).attr('id') ){

    if( prev != '' ){

        $("#"+prev).prop('checked',true);

        prev = '';

    }

    return;

  }

  prev = curr;

  curr = $(this).attr('id');

});

html:

<input id="rad1" value="1" type="radio" name="rad"/><label for="rad1">Radio 1</label>
<input id="rad2" value="2" type="radio" name="rad"/><label for="rad2">Radio 2</label>
<input id="rad3" value="3" type="radio" name="rad"/><label for="rad3">Radio 3</label>

Fiddle

相关问题