html 의 확인란 하나만 선택해야 그룹

그래서 사용자가 하나만 선택할 수 있도록 확인란 미디어만을 어떻게 해야 합니까?

그러니까말이야 라디오 버튼은 &quot ideal&quot 있으나, purpose.it & # 39,, 내 일은 아닙니다.

I have a 필드로 둘 중 하나를 선택해야 하는 사용자 또는 두 가지 옵션이 있다. 문제는 데릭쉐퍼드와 사용자들은 그들의 수 있을 수도 있기 때문에, 이 옵션을 선택하면 선택취소할 대화상자에서는 라디오 단추 페일오버합니다 그룹화할 옵션을 선택하여 합니다.

내아기마저도 수 있지만, 아직도; d # 39 I& 검증중 정보 php 를 통해 사용자가 원할 경우 제한하는 대답을 하나 봐 주세요.

질문에 대한 의견 (6)
해결책

이 스니펫은:

라디오 단추 등 허용하시겠습니까 그룹화하면 -

  • 라디오 처럼 행동하는
  • 모든 허용하시겠습니까 선택 취소

<! - begin 스니핏: js 숨기십시오: &gt 거짓값 -;

// 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>

    <input type="checkbox" class="radio" value="1" name="fooby[1][]" />Kiwi

    <input type="checkbox" class="radio" value="1" name="fooby[1][]" />Jackfruit

    <input type="checkbox" class="radio" value="1" name="fooby[1][]" />Mango
</div>
<div>
  <h3>Animals</h3>

    <input type="checkbox" class="radio" value="1" name="fooby[2][]" />Tiger

    <input type="checkbox" class="radio" value="1" name="fooby[2][]" />Sloth

    <input type="checkbox" class="radio" value="1" name="fooby[2][]" />Cheetah
</div>

끝 - &lt 스니핏 >;!

해설 (10)

39 바인딩하려면 you&; d 'a' () 이 행사는 불지옥의 상태를 변경할 수 있도록 처리기에서 때 확인란 변경. 그럼 그냥 별도로 있는 한 모든 확인란 선택해제합니다 트리거되면 이 처리기에서:

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

[Here& s # 39, 피들] (http://jsfiddle.net/X597P/)

같은 경우, 그룹화용으로 확인란 &quot groups"; 이미 모두 다음과 같은 뜻을 지닌다.

<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);
});

[Here& # 39 의 또 다른 바이올린] (http://jsfiddle.net/X597P/9/)

다른 사람이 같은 경우 확인란 그룹화됩니다 속성용 "이름":

<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);
});

[Here& # 39 의 또 다른 바이올린] (http://jsfiddle.net/EB2qC/1/)

해설 (8)

라디오 단추 것이 바람직합니다. 방금 제 3, neither&quot &quot 합니다. 이는 기본적으로 옵션을 선택합니다.

해설 (6)

하지만 누구도 그들을 따라 몇 가지 답을 이미 이 같은 그들을 위한 JS 순결케 상당하다는 싶다 수 있다.

내 솔루션이므로 슬라이드에서는 사용에 따른 이름 태그 () 로 라디오 버튼) 와 몇 줄의 javascript.

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. &gt 거짓값 -;

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)">

끝 - &lt 스니핏 >;!

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

이 형식으로 수에 상관없이 확인란 노력해야 합니다. # 39 aren& 있는 경우, t, 다른 그룹의 일부가 선택기를 설정되었습니다 해당 투입물.

해설 (2)

다음은 간단한 HTML 및 JavaScript 솔루션이므로 이 더 좋아요.

평일 확인란 //js 기능을 한 번에 1 만 허용 검사:

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   
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Tuesday" />Tue   
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Wednesday" />Wed   
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Thursday" />Thu   
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Friday" />Fri   
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Saturday" />Sat   
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Sunday" />Sun   <br /><br />
해설 (0)

이 코드는 큰 도움이 될 수 있습니다.

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. &gt 거짓값 -;

$(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...!');
});
});



<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>



<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>

끝 - &lt 스니핏 >;!

Apc® 링크 [여기를 클릭] [1]

[1]: http://www.w3schools.com/code/tryit.asp = FB6JK5HW3Z53 파일_이름?

해설 (0)

& # 39 의 구축에 대한 [빌리오네캉] [1] 라고 하는 경우, 다음과 같은 코드를 사용할 수 있습니다 스니핏 있는 둘 이상의 확인란 사용한다고 가정할 때 서로 다른 이름).

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

[1]: https://stackoverflow.com/users/1087721/billyonecan &quot billyonecan";

해설 (0)
  • 예와 함께 앙굴라이스 *

<! - begin 스니핏: js 숨기십시오: &gt 거짓값 -;

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




  <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>



  SELECTED: {{selected}}
  <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>



끝 - &lt 스니핏 >;!

해설 (0)

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 거짓값 바벨. &gt 거짓값 -;

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




  <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>



  SELECTED: {{selected}}
  <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>

끝 - &lt 스니핏 >;!

해설 (0)

누군가 이 슬라이드에서는 외부 자바스크립트 라이브러리 솔루션 필요 없이 사용할 수 있습니다. 한 무리의 확인란 0.1 값을 수 있습니다. 확인란 추가했습니까 아니면 텍스트 관련 레이블 클릭할 수 있습니다.


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

- - - - - - - - 

    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
해설 (0)

, 길을 갈 수 있는 반면 JS 는 아마도 이 수행될 HTML 과 CSS 뿐입니다.

여기 진짜 진짜 숨겨짐 라디오 버튼를 원하는거요 라디오 버튼를 투명지에 가짜 라벨. 이렇게 해서 꼭 필요한 효과를 얻을 수 있습니다.


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


<div id='uncheck'>
  <input type="radio" name='food' id="box1" /> 
  Pizza 
    ◎ 
    ◉
  <input type="radio" name='food' id="box2" /> 
  Ice cream 
    ◎ 
    ◉
  <input type="radio" name='food' id="box0" checked />
</div>

그것을 볼 수 있습니다. https://jsfiddle.net/tn70yxL8/2/

현재 남아 있는 레이블 비사양 선택할 수 있는 합니다.

이 경우 기술적으로 방지할 수 있습니다, 라벨, 포함시키십시오 조교하실 기꺼이 리피팅 &quot uncheck&quot. css 를 변경하여 레이블에만 텍스트를 볼 수 있습니다. https://jsfiddle.net/7tdb6quy/2/

해설 (0)

내 버전: javascript 를 사용하여 데이터 특성 및 바닐라

<div class="test-checkbox">
    Group One: 
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Eat" />Eat

        <input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Sleep" />Sleep

        <input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Play" />Play
    <br />
    Group Two: 
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Fat" />Fat

        <input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Comfort" />Comfort

        <input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Happy" />Happy
</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>
해설 (0)

네크로맨스링: br /&gt <; , JQuery 의 다음과 같은 구조 및 없이 확인란


<input type="checkbox" id="mytrackers_1" name="blubb_1" value="">--- Bitte auswählen ---


<input type="checkbox" id="mytrackers_2" name="blubb_2" value="7">Testtracker


<input type="checkbox" id="mytrackers_3" name="blubb_3" value="3">Kundenanfrage


<input type="checkbox" id="mytrackers_4" name="blubb_4" value="2">Anpassung


<input type="checkbox" id="mytrackers_5" name="blubb_5" value="1" checked="checked" >Fehler


<input type="checkbox" id="mytrackers_6" name="blubb_6" value="4">Bedienung


<input type="checkbox" id="mytrackers_7" name="blubb_7" value="5">Internes


<input type="checkbox" id="mytrackers_8" name="blubb_8" value="6">Änderungswunsch

이렇게 하면 안 됩니다.

    /// 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 
        // https://stackoverflow.com/questions/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 ((node).matches(childSelector))
                // else console.log("no match");
            } // End if ((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;
    }

    // https://stackoverflow.com/questions/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;
해설 (0)
//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>
해설 (0)