Only one checkbox checked at a time in javascript

前端 未结 2 1944
说谎
说谎 2021-01-26 05:41

I have 3 checkbox, for which I want only 1 checkbox to be checked at a time. below is my fiddle for the html

JS fiddle

I want this to b

相关标签:
2条回答
  • 2021-01-26 06:00

    function selectOnlyThis(id) {
        for (var i = 1;i <= 4; i++)
        {
            document.getElementById(i).checked = false;
        }
        document.getElementById(id).checked = true;
    }
    <input type="checkbox" id="1" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 1
    <input type="checkbox" id="2" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 2
    <input type="checkbox" id="3" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 3
    <input type="checkbox" id="4" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 4

    It should help you

    0 讨论(0)
  • 2021-01-26 06:05

    How about this - fiddle:

    <input type="checkbox" class="chk" />
    <input type="checkbox" class="chk" />
    <input type="checkbox" class="chk" />
    <input type="checkbox" class="chk" />
    
    $('input.chk').on('change', function() {
        $('input.chk').not(this).prop('checked', false);  
    });
    

    Edit: for second part of your question to un-check other checkboxes when selecting parent checkbox see this fiddle - (as per chat) :

    if (!cb.checked) { 
    $('#trchkOptions input[type=checkbox]').attr('checked', false); 
    }
    
    0 讨论(0)
提交回复
热议问题