Only one selected checkbox

后端 未结 8 1782
梦毁少年i
梦毁少年i 2021-01-14 05:17

I have 15 check boxes in a form. This checkboxes are independent to eachother. I want a javascript function that makes, when user is selecting 2 checkboxes, the first checke

相关标签:
8条回答
  • 2021-01-14 05:45

    Check Fiddle

    1. Give name of you checkboxs let 'myCheckbox'.
    2. On click of checkbox loop through all checkbox with name 'myCheckbox';
    3. make 'myCheckbox' uncheck.
    4. make Clicked Checkbox checked.

    HTML

    <input type="checkbox" name="myCheckbox" value="1" onclick="selectOnlyThis(this)" />
    <input type="checkbox" name="myCheckbox" value="2" onclick="selectOnlyThis(this)"/>
    <input type="checkbox" name="myCheckbox" value="3" onclick="selectOnlyThis(this)"/>
    

    JavaScript

    function selectOnlyThis(id){
      var myCheckbox = document.getElementsByName("myCheckbox");
      Array.prototype.forEach.call(myCheckbox,function(el){
        el.checked = false;
      });
      id.checked = true;
    }
    
    0 讨论(0)
  • 2021-01-14 05:47

    Would you be better off using radio buttons instead of checkboxes as per this site: http://www.echoecho.com/htmlforms10.htm?

    If you want to use check boxes I guess you could do something like this:

    HTML Code:

    <input type="checkbox" id="Check1" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 1
    <input type="checkbox" id="Check2" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 2
    <input type="checkbox" id="Check3" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 3
    <input type="checkbox" id="Check4" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 4
    

    Javascript Code :

    function selectOnlyThis(id) {
        for (var i = 1;i <= 4; i++)
        {
            document.getElementById("Check" + i).checked = false;
        }
        document.getElementById(id).checked = true;
    }
    
    0 讨论(0)
提交回复
热议问题