html 그룹에서 하나의 확인란 만 선택


125

그렇다면 사용자가 하나의 확인란 만 선택하도록 허용하려면 어떻게해야합니까?

라디오 버튼이 "이상적"이라는 것을 알고 있지만 제 목적으로는 그렇지 않습니다.

사용자가 두 옵션 중 하나 또는 둘 중 하나만 선택해야하는 필드가 있습니다. 문제는 내 사용자가 옵션 선택을 취소 할 수 있어야한다는 것입니다. 여기에서 그룹을 선택하면 옵션을 선택해야하므로 라디오 버튼이 실패합니다.

나는 php를 통해 정보의 유효성을 검사 할 것이지만, 그들이 그것을 제공하고 싶다면 여전히 사용자를 하나의 답변으로 제한하고 싶습니다.


1
HTML만으로는 할 수 없습니다. JavaScript가 필요합니다. jQuery에 개방적이라면 빠른 솔루션을 제공 할 수 있습니다.
Surreal Dreams

12
"없음"이라고 표시된 추가 라디오 버튼은 어떻습니까?
FelipeAls

2
세 번째 옵션은 내 디자인과 잘 맞지 않습니다. 그래도 좋은 대안입니다. :)
user962449

2
단일 선택이있는 체크 박스는 실제로 라디오 버튼입니다. 이것은 사용자를 놀라게하지 않을까요?
Gherman

@Surreal Dreams HTML로 할 수 있습니다. 내 대답을 참조하십시오. 하지만 대부분의 경우 JS는 더 간단하고 해킹이 필요하지 않습니다.
SamGoody

답변:


179

이 스 니펫은 다음을 수행합니다.

  • 라디오 버튼과 같은 그룹화 허용
  • 라디오처럼 행동
  • 모두 선택 취소 허용

// the selector will match all input controls of type :checkbox
// and attach a click event handler 
$("input:checkbox").on('click', function() {
  // in the handler, 'this' refers to the box clicked on
  var $box = $(this);
  if ($box.is(":checked")) {
    // the name of the box is retrieved using the .attr() method
    // as it is assumed and expected to be immutable
    var group = "input:checkbox[name='" + $box.attr("name") + "']";
    // the checked state of the group/box on the other hand will change
    // and the current value is retrieved using .prop() method
    $(group).prop("checked", false);
    $box.prop("checked", true);
  } else {
    $box.prop("checked", false);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<div>
  <h3>Fruits</h3>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[1][]" />Kiwi</label>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[1][]" />Jackfruit</label>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[1][]" />Mango</label>
</div>
<div>
  <h3>Animals</h3>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[2][]" />Tiger</label>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[2][]" />Sloth</label>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[2][]" />Cheetah</label>
</div>


3
올바른 사용법은 $ (this) .is ( ": checked") "is"를 사용하여 if {...} else {...} here ... jsfiddle 에서 확인란이 선택되었는지 확인하는 것입니다. .net / zGEaa / 31
sergioadh

2
.attr이 더 이상 작동하지 않습니다. 새 버전의 jQuery
user871784

@ user871784-미리 알려 주셔서 감사합니다 ... 바이올린을 업데이트했습니다!
bPratik 2013 년

3
라디오 선택기를 놓쳤습니다. $ ( "input : checkbox.radio")
Sven

@Sven-이 예에서는 지나치게 구체적인 선택자입니다. 페이지에이 동작이 없어야하는 다른 확인란 집합이 포함되어있는 경우 .radio선택기 를 사용하면 도움이됩니다. 지적 해 주셔서 감사합니다 :)
bPratik

101

change()확인란의 상태가 변경 될 때 이벤트가 발생하도록 핸들러 를 바인딩하고 싶습니다 . 그런 다음 핸들러를 트리거 한 체크 박스를 제외한 모든 체크 박스를 선택 취소합니다.

$('input[type="checkbox"]').on('change', function() {
   $('input[type="checkbox"]').not(this).prop('checked', false);
});

여기 바이올린이 있습니다


그룹화의 경우 "그룹"확인란이 모두 형제 인 경우 :

<div>
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
</div>  
<div>
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
</div>   
<div>
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
</div>

다음과 같이 할 수 있습니다.

$('input[type="checkbox"]').on('change', function() {
   $(this).siblings('input[type="checkbox"]').prop('checked', false);
});

여기 또 다른 바이올린이 있습니다


체크 박스가 다음과 같은 다른 속성으로 그룹화 된 경우 name:

<input type="checkbox" name="group1[]" />
<input type="checkbox" name="group1[]" />
<input type="checkbox" name="group1[]" />

<input type="checkbox" name="group2[]" />
<input type="checkbox" name="group2[]" />
<input type="checkbox" name="group2[]" />

<input type="checkbox" name="group3[]" />
<input type="checkbox" name="group3[]" />
<input type="checkbox" name="group3[]" />

다음과 같이 할 수 있습니다.

$('input[type="checkbox"]').on('change', function() {
    $('input[name="' + this.name + '"]').not(this).prop('checked', false);
});

여기 또 다른 바이올린이 있습니다


나는 당신의 (마지막) 코드를 좋아합니다. 매우 짧고 여전히 명확합니다. 다른 확인란을 변경하면 '변경'이 실행되는지 확실하지 않았지만 시도했을 때는 그렇지 않았습니다. 그래서 나는 당신의 코드를 선호합니다. 감사! :)
Frank Fajardo 2015 년

나는 이것을 정말로 좋아한다. 나는 나의 필요에 대해 약간의 조정을해야한다. 두 개의 항목이 있으므로 첫 번째 항목은 기본적으로 선택되어 있고 선택하지 않으면 두 번째 항목이 선택됩니다. 이것은 제가 시작하는 데 도움이되었습니다.
john.weland

안녕하세요 @ john.weland- 이런 뜻 인가요?
billyonecan 16.01.14

@billyone은 거의 정확하지만 주어진 그룹을 대상으로 할 수 있습니다. 이렇게 . 감사합니다
john.weland

2
플러스 간단 하나
차드

26

라디오 버튼이 이상적입니다. 기본적으로 선택되는 세 번째 "둘 다 아님"옵션 만 있으면됩니다.


1
그것은 좋은 해결책이지만 제 디자인이 세 번째 옵션에 이상적이지 않기 때문에 체크 박스를 사용하는 편입니다.
user962449 2012 년

6
디자인을 변경하는 것이 좋습니다. 이 두 가지 옵션 중 0 또는 1을 선택 하는 것은 일반적인 패턴이 아니며 사용자
Quentin

4
2 개의 체크 박스에 대한 전체 디자인을 변경하는 이유는 무엇입니까?
user962449 2012 년

9
이러한 변경으로 인해 "전체 디자인"을 변경해야한다면 처음에는 디자인이 너무 유연하지 않다는 것을 의미합니다.
Quentin

10
유연하지 않고 옳지 않은 것 같습니다 ... 양식과 그러한 응용 프로그램에서는 괜찮아 보일 수 있지만 확인란에 대한 용도가 다릅니다.
user962449 2012 년

13

순수한 JS를 기반으로 한 이에 대한 몇 가지 답변이 이미 있지만 그중 어느 것도 내가 원하는만큼 간결하지 않습니다.

다음은 이름 태그 (라디오 버튼과 마찬가지로)와 몇 줄의 자바 스크립트 사용을 기반으로 한 솔루션입니다.

function onlyOne(checkbox) {
    var checkboxes = document.getElementsByName('check')
    checkboxes.forEach((item) => {
        if (item !== checkbox) item.checked = false
    })
}
<input type="checkbox" name="check" onclick="onlyOne(this)">
<input type="checkbox" name="check" onclick="onlyOne(this)">
<input type="checkbox" name="check" onclick="onlyOne(this)">
<input type="checkbox" name="check" onclick="onlyOne(this)">


감사합니다,이 하나) = 모든 다른 사람으로부터 나를 위해 그것을 한
가야

6
$("#myform input:checkbox").change(function() {
    $("#myform input:checkbox").attr("checked", false);
    $(this).attr("checked", true);
});

이것은 양식의 여러 확인란에 대해 작동합니다. 그룹에 속하지 않는 다른 사람이있는 경우 선택기를 해당 입력으로 설정합니다.


네 선생님 :) 괜찮습니다. 귀하의 솔루션이 매우 간단 해 보이지만 저에게 맞는 것을 찾았습니다. 내 쪽에서 뭔가 잘못했을 것입니다. 어쨌든 고마워.
user962449 2012 년

5

내가 선호하는 간단한 HTML 및 JavaScript 솔루션은 다음과 같습니다.

// js 함수를 사용하여 한 번에 하나의 주중 확인란 만 확인할 수 있습니다.

function checkOnlyOne(b){

var x = document.getElementsByClassName('daychecks');
var i;

for (i = 0; i < x.length; i++) {
  if(x[i].value != b) x[i].checked = false;
}
}


Day of the week:
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Monday" />Mon&nbsp;&nbsp;&nbsp;
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Tuesday" />Tue&nbsp;&nbsp;&nbsp;
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Wednesday" />Wed&nbsp;&nbsp;&nbsp;
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Thursday" />Thu&nbsp;&nbsp;&nbsp;
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Friday" />Fri&nbsp;&nbsp;&nbsp;
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Saturday" />Sat&nbsp;&nbsp;&nbsp;
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Sunday" />Sun&nbsp;&nbsp;&nbsp;<br /><br />

4

이 코드가 도움이되기를 바랍니다.

$(document).ready(function(){
$('.slectOne').on('change', function() {
   $('.slectOne').not(this).prop('checked', false);
   $('#result').html($(this).data( "id" ));
   if($(this).is(":checked"))
   	$('#result').html($(this).data( "id" ));
   else
   	$('#result').html('Empty...!');
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

</head>
<body>
<input type="checkbox" class="slectOne" data-id="1 selected"/>
<input type="checkbox" class="slectOne" data-id="2 selected"/>
<input type="checkbox" class="slectOne" data-id="3 selected"/>
<input type="checkbox" class="slectOne" data-id="4 selected"/>
<input type="checkbox" class="slectOne" data-id="5 selected"/>
<input type="checkbox" class="slectOne" data-id="6 selected"/>
<input type="checkbox" class="slectOne" data-id="7 selected"/>
<input type="checkbox" class="slectOne" data-id="8 selected"/>
<input type="checkbox" class="slectOne" data-id="9 selected"/>
<input type="checkbox" class="slectOne" data-id="10 selected"/>
<span id="result"></span>
</body>
</html>

작업 링크 여기를 클릭하십시오


3

billyonecan 의 답변 을 바탕 으로 두 개 이상의 확인란에 해당 코드가 필요한 경우 다음 코드를 사용할 수 있습니다 (이름이 다른 경우).

    $('input.one').on('change', function() {
        var name = $(this).attr('name');
        $('input[name='+name+'].one').not(this).prop('checked', false);
    }); 

3

JS는 아마도 갈 길이지만 HTML과 CSS로만 할 있습니다.

여기에 진짜 숨겨진 라디오 버튼의 레이블 인 가짜 라디오 버튼이 있습니다. 그렇게함으로써 필요한 효과를 정확히 얻을 수 있습니다.

<style>
   #uncheck>input { display: none }
   input:checked + label { display: none }
   input:not(:checked) + label + label{ display: none } 
</style>

<div id='uncheck'>
  <input type="radio" name='food' id="box1" /> 
  Pizza 
    <label for='box1'>&#9678;</label> 
    <label for='box0'>&#9673;</label>
  <input type="radio" name='food' id="box2" /> 
  Ice cream 
    <label for='box2'>&#9678;</label> 
    <label for='box0'>&#9673;</label>
  <input type="radio" name='food' id="box0" checked />
</div>

여기에서 확인하세요 : https://jsfiddle.net/tn70yxL8/2/

이제 선택 불가능한 레이블이 필요하다고 가정합니다.

레이블을 포함하려는 경우 CSS에서 텍스트를 변경하여 "선택 취소"레이블을 반복하는 것을 기술적으로 피할 수 있습니다. 여기를 참조하십시오. https://jsfiddle.net/7tdb6quy/2/


1

AngularJs를 사용한 예

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <script>
    angular.module('app', []).controller('appc', ['$scope',
      function($scope) {
        $scope.selected = 'other';
      }
    ]);
  </script>
</head>

<body ng-app="app" ng-controller="appc">
  <label>SELECTED: {{selected}}</label>
  <div>
    <input type="checkbox" ng-checked="selected=='male'" ng-true-value="'male'" ng-model="selected">Male
    <br>
    <input type="checkbox" ng-checked="selected=='female'" ng-true-value="'female'" ng-model="selected">Female
    <br>
    <input type="checkbox" ng-checked="selected=='other'" ng-true-value="'other'" ng-model="selected">Other
  </div>



</body>

</html>


1

평범한 오래된 자바 스크립트로.

<html>
<head>
</head>
<body>
<input type="checkbox" name="group1[]" id="groupname1" onClick="toggle(1,'groupname')"/>
<input type="checkbox" name="group1[]" id="groupname2" onClick="toggle(2,'groupname')"  />
<input type="checkbox" name="group1[]" id="groupname3" onClick="toggle(3,'groupname')" />

<input type="checkbox" name="group2[]" id="diffGroupname1" onClick="toggle(1,'diffGroupname')"/>
<input type="checkbox" name="group2[]" id="diffGroupname2" onClick="toggle(2,'diffGroupname')"  />
<input type="checkbox" name="group2[]" id="diffGroupname3" onClick="toggle(3,'diffGroupname')" />
<script>
function toggle(which,group){
var counter=1;
var checkbox=document.getElementById(group+counter);
while(checkbox){
if(counter==which){

}else{
checkbox.checked=false;
}
counter++;
checkbox=document.getElementById(group+counter);
}
}
</script>
</body>
</html>

편집 : 또한 가능

<html>
<head>
</head>
<body>
<input type="checkbox" name="group1[]" class="groupname" onClick="toggle(this,'groupname')"/>
<input type="checkbox" name="group1[]" class="groupname" onClick="toggle(this,'groupname')"  />
<input type="checkbox" name="group1[]" class="groupname" onClick="toggle(this,'groupname')" />

<input type="checkbox" name="group2[]" class="diffGroupname" onClick="toggle(this,'diffGroupname')"/>
<input type="checkbox" name="group2[]" class="diffGroupname" onClick="toggle(this,'diffGroupname')"  />
<input type="checkbox" name="group2[]" class="diffGroupname" onClick="toggle(this,'diffGroupname')" />
<script>
function toggle(which,theClass){
var checkbox=document.getElementsByClassName(theClass);
for(var i=0;i<checkbox.length;i++){
if(checkbox[i]==which){

}else{
checkbox[i].checked=false;
}
}
}
</script>
</body>
</html>

0

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <script>
    angular.module('app', []).controller('appc', ['$scope',
      function($scope) {
        $scope.selected = 'male';
      }
    ]);
  </script>
</head>

<body ng-app="app" ng-controller="appc">
  <label>SELECTED: {{selected}}</label>
  <div>
    <input type="checkbox" ng-checked="selected=='male'" ng-true-value="'male'" ng-model="selected">Male
    <br>
    <input type="checkbox" ng-checked="selected=='female'" ng-true-value="'female'" ng-model="selected">Female
    <br>
    <input type="checkbox" ng-checked="selected=='other'" ng-true-value="'other'" ng-model="selected">Other
  </div>
</body>
</html>


0

누군가 외부 자바 스크립트 라이브러리가없는 솔루션이 필요한 경우이 예제를 사용할 수 있습니다. 0..1 값을 허용하는 확인란 그룹입니다. 확인란 구성 요소 또는 관련 레이블 텍스트를 클릭 할 수 있습니다.

    <input id="mygroup1" name="mygroup" type="checkbox" value="1" onclick="toggleRadioCheckbox(this)" /> <label for="mygroup1">Yes</label>
    <input id="mygroup0" name="mygroup" type="checkbox" value="0" onclick="toggleRadioCheckbox(this)" /> <label for="mygroup0">No</label>

- - - - - - - - 

    function toggleRadioCheckbox(sender) {
        // RadioCheckbox: 0..1 enabled in a group 
        if (!sender.checked) return;
        var fields = document.getElementsByName(sender.name);
        for(var idx=0; idx<fields.length; idx++) {
            var field = fields[idx];
            if (field.checked && field!=sender)
                field.checked=false;
        }
    }

0

내 버전 : 데이터 속성 및 Vanilla JavaScript 사용

<div class="test-checkbox">
    Group One: <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Eat" />Eat</label>
    <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Sleep" />Sleep</label>
    <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Play" />Play</label>
    <br />
    Group Two: <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Fat" />Fat</label>
    <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Comfort" />Comfort</label>
    <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Happy" />Happy</label>
</div>
<script>
    let cbxes = document.querySelectorAll('input[type="checkbox"][data-limit="only-one-in-a-group"]');
    [...cbxes].forEach((cbx) => {
        cbx.addEventListener('change', (e) => {
            if (e.target.checked)
                uncheckOthers(e.target);
        });
    });
    function uncheckOthers (clicked) {
        let name = clicked.getAttribute('name');
        // find others in same group, uncheck them
        [...cbxes].forEach((other) => {
            if (other != clicked && other.getAttribute('name') == name)
                other.checked = false;
        });
    }
</script>

-1

Necromancing : 다음
과 같은 체크 박스 구조의 경우 jQuery 없이 :

<label>
<input type="checkbox" id="mytrackers_1" name="blubb_1" value="">--- Bitte ausw&#228;hlen ---
</label>
<label>
<input type="checkbox" id="mytrackers_2" name="blubb_2" value="7">Testtracker
</label>
<label>
<input type="checkbox" id="mytrackers_3" name="blubb_3" value="3">Kundenanfrage
</label>
<label>
<input type="checkbox" id="mytrackers_4" name="blubb_4" value="2">Anpassung
</label>
<label>
<input type="checkbox" id="mytrackers_5" name="blubb_5" value="1" checked="checked" >Fehler
</label>
<label>
<input type="checkbox" id="mytrackers_6" name="blubb_6" value="4">Bedienung
</label>
<label>
<input type="checkbox" id="mytrackers_7" name="blubb_7" value="5">Internes
</label>
<label>
<input type="checkbox" id="mytrackers_8" name="blubb_8" value="6">&#196;nderungswunsch
</label>

다음과 같이 할 수 있습니다.

    /// attach an event handler, now or in the future, 
    /// for all elements which match childselector,
    /// within the child tree of the element maching parentSelector.
    function subscribeEvent(parentSelector, eventName, childSelector, eventCallback) {
        if (parentSelector == null)
            throw new ReferenceError("Parameter parentSelector is NULL");
        if (childSelector == null)
            throw new ReferenceError("Parameter childSelector is NULL");
        // nodeToObserve: the node that will be observed for mutations
        var nodeToObserve = parentSelector;
        if (typeof (parentSelector) === 'string')
            nodeToObserve = document.querySelector(parentSelector);
        var eligibleChildren = nodeToObserve.querySelectorAll(childSelector);
        for (var i = 0; i < eligibleChildren.length; ++i) {
            eligibleChildren[i].addEventListener(eventName, eventCallback, false);
        } // Next i 
        // /programming/2712136/how-do-i-make-this-loop-all-children-recursively
        function allDescendants(node) {
            if (node == null)
                return;
            for (var i = 0; i < node.childNodes.length; i++) {
                var child = node.childNodes[i];
                allDescendants(child);
            } // Next i 
            // IE 11 Polyfill 
            if (!Element.prototype.matches)
                Element.prototype.matches = Element.prototype.msMatchesSelector;
            if (node.matches) {
                if (node.matches(childSelector)) {
                    // console.log("match");
                    node.addEventListener(eventName, eventCallback, false);
                } // End if ((<Element>node).matches(childSelector))
                // else console.log("no match");
            } // End if ((<Element>node).matches) 
            // else console.log("no matchfunction");
        } // End Function allDescendants 
        // Callback function to execute when mutations are observed
        var callback = function (mutationsList, observer) {
            for (var _i = 0, mutationsList_1 = mutationsList; _i < mutationsList_1.length; _i++) {
                var mutation = mutationsList_1[_i];
                // console.log("mutation.type", mutation.type);
                // console.log("mutation", mutation);
                if (mutation.type == 'childList') {
                    for (var i = 0; i < mutation.addedNodes.length; ++i) {
                        var thisNode = mutation.addedNodes[i];
                        allDescendants(thisNode);
                    } // Next i 
                } // End if (mutation.type == 'childList') 
                // else if (mutation.type == 'attributes') { console.log('The ' + mutation.attributeName + ' attribute was modified.');
            } // Next mutation 
        }; // End Function callback 
        // Options for the observer (which mutations to observe)
        var config = { attributes: false, childList: true, subtree: true };
        // Create an observer instance linked to the callback function
        var observer = new MutationObserver(callback);
        // Start observing the target node for configured mutations
        observer.observe(nodeToObserve, config);
    } // End Function subscribeEvent 


    function radioCheckbox_onClick() 
    { 
        // console.log("click", this);
        let box = this;
        if (box.checked) 
        {
            let name = box.getAttribute("name");
            let pos = name.lastIndexOf("_");
            if (pos !== -1) name = name.substr(0, pos);

            let group = 'input[type="checkbox"][name^="' + name + '"]';
            // console.log(group);
            let eles = document.querySelectorAll(group);
            // console.log(eles);
            for (let j = 0; j < eles.length; ++j) 
            {
                eles[j].checked = false;
            }
            box.checked = true;
        }
        else
            box.checked = false;
    }


    // /programming/9709209/html-select-only-one-checkbox-in-a-group
    function radioCheckbox()
    { 
        // on instead of document...
        let elements = document.querySelectorAll('input[type="checkbox"]')

        for (let i = 0; i < elements.length; ++i)
        {
            // console.log(elements[i]);
            elements[i].addEventListener("click", radioCheckbox_onClick, false);

        } // Next i 

    } // End Function radioCheckbox 


    function onDomReady()
    {
        console.log("dom ready");
        subscribeEvent(document, "click", 
            'input[type="checkbox"]', 
            radioCheckbox_onClick
        ); 

        // radioCheckbox();
    }

    if (document.addEventListener) document.addEventListener("DOMContentLoaded", onDomReady, false);
    else if (document.attachEvent) document.attachEvent("onreadystatechange", onDomReady);
    else window.onload = onDomReady;

    function onPageLoaded() {
        console.log("page loaded");
    }

    if (window.addEventListener) window.addEventListener("load", onPageLoaded, false);
    else if (window.attachEvent) window.attachEvent("onload", onPageLoaded);
    else window.onload = onPageLoaded;

-1
//Here is a solution using JQuery    
<input type = "checkbox" class="a"/>one
    <input type = "checkbox" class="a"/>two
    <input type = "checkbox" class="a"/>three
    <script>
       $('.a').on('change', function() {
            $('.a').not(this).prop('checked',false);
    });
    </script>
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.