使复选框的行为类似于使用javascript的单选按钮

问题描述 投票:21回答:10

我需要使用javascript操纵复选框的行为。它们基本上应该像单选按钮一样(一次只能选择一个,再取消选择以前的选择)。

问题是我不能首先使用普通的单选按钮,因为每个单选按钮的名称属性会有所不同。

我知道它不是使苹果看起来像梨的最终和最闪亮的解决方案,并且w3c不会让我大拇指,但它现在比改变整个cms的核心php逻辑更好的解决方案结构体 ;-)

任何帮助深表感谢!

javascript html
10个回答
65
投票

HTML:

<label><input type="checkbox" name="cb1" class="chb" /> CheckBox1</label>
<label><input type="checkbox" name="cb2" class="chb" /> CheckBox2</label>
<label><input type="checkbox" name="cb3" class="chb" /> CheckBox3</label>
<label><input type="checkbox" name="cb4" class="chb" /> CheckBox4</label>

jQuery:

$(".chb").change(function() {
    $(".chb").prop('checked', false);
    $(this).prop('checked', true);
});

如果您希望用户可以取消选中所选项目:

$(".chb").change(function() {
    $(".chb").not(this).prop('checked', false);
});

演示:

http://jsfiddle.net/44Zfv/724/


0
投票

我喜欢D.A.V.O.O.D's Answer to this question,但它依赖于复选框上的类,这不应该是必需的。

因为复选框往往是相关的,因为它们将具有相同的(字段)名称,或者使它们成为数组的一部分的名称,然后使用它来决定取消哪个其他复选框将是更好的解决方案。

$(document)
  .on('change','input[type="checkbox"]',function(e){
    var $t = $(this);
    var $form = $t.closest('form');
    var name = $t.attr('name');
    var selector = 'input[type="checkbox"]';
    var m = (new RegExp('^(.+)\\[([^\\]]+)\\]$')).exec( name );
    if( m ){
      selector += '[name^="'+m[1]+'["][name$="]"]';
    }else{
      selector += '[name="'+name+'"]';
    }
    $(selector, $form).not($t).prop('checked',false);
  });

This code on jsFiddle


5
投票

有很多方法可以做到这一点。这是一个包含许多复选框的div的clickhandler(plain js):

function cbclick(e){
   e = e || event;
   var cb = e.srcElement || e.target;
   if (cb.type !== 'checkbox') {return true;}
   var cbxs = document.getElementById('radiocb')
               .getElementsByTagName('input'), 
       i    = cbxs.length;
    while(i--) {
        if (cbxs[i].type 
             && cbxs[i].type == 'checkbox' 
             && cbxs[i].id !== cb.id) {
          cbxs[i].checked = false;
        }
    }
}

这是a working example


4
投票

我保持简单......

<html>
<body>

<script>
function chbx(obj)
{
var that = obj;
   if(document.getElementById(that.id).checked == true) {
      document.getElementById('id1').checked = false;
      document.getElementById('id2').checked = false;
      document.getElementById('id3').checked = false;
      document.getElementById(that.id).checked = true;
   }
}
</script>

<form action="your action" method="post">

<Input id='id1' type='Checkbox' Name ='name1' value ="S" onclick="chbx(this)"><br />
<Input id='id2' type='Checkbox' Name ='name2' value ="S" onclick="chbx(this)"><br />
<Input id='id3' type='Checkbox' Name ='name3' value ="S" onclick="chbx(this)"><br />

<input type="submit" value="Submit" />
</form>

</body>
</html>

4
投票

这是一个更好的选择,因为它还允许取消选中:

$(".cb").change(function () {
    $(".cb").not(this).prop('checked', false);
});

1
投票

您可以将您需要的复选框组作为一个公共类,然后使用该类附加以下事件处理程序:

function clickReset ()
{
    var isChecked = false,
        clicked = $(this),
        set = $('.' + clicked.attr ('class') + ':checked').not (clicked);

    if (isChecked = clicked.attr ('checked'))
    {
        set.attr ('checked', false);
    }
    return true;
}

$(function ()
{
    $('.test').click (clickReset);
});

注意:这对我来说只是从臀部拍摄,我没有对此进行测试,可能需要调整才能工作。

如果可以的话,我建议您确实使用单选按钮来寻找一种方法,因为无线电是适合这项工作的工具。用户希望复选框的行为类似于复选框,而不是无线电,如果他们关闭javascript,他们可以强制通过输入到您不期望的服务器端脚本。

编辑:修复功能,以便取消选中正常工作并添加JS Fiddle链接。

http://jsfiddle.net/j53gd/1/


1
投票

以防万一它可以帮助别人

我有同样的情况,我的客户需要有一个checkbox表现得像radio button。但对我而言,使用checkbox使其像radio button一样毫无意义,这对我来说非常复杂,因为我在checkboxes Control中使用了这么多的GridView

我的解决方案 因此,我设计了一个radio button看起来像checkbox并采取了grouping的单选按钮的帮助。


0
投票
<html>
<body>

<form action="#" method="post">
Radio 1: <input type="radio" name="radioMark" value="radio 1" /><br />
Radio 2: <input type="radio" name="radioMark" value="radio 2" /><br />
<input type="submit" value="Submit" />
</form>

</body>
</html>

最终你可以使用带有name属性的括号来创建一个无线电输入数组,如下所示:

<input type="radio" name="radioMark[]" value="radio1" />Radio 1
<input type="radio" name="radioMark[]" value="radio2" />Radio 2
<input type="radio" name="radioMark[]" value="radio3" />Radio 3
<input type="radio" name="radioMark[]" value="radio4" />Radio 4

最后转移的重点是value属性中的什么。每个单选按钮的名称不必完全不同。希望有所帮助。


0
投票

在Simple JS中。请享用 !

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
        function onChoiceChange(obj) {
            // Get Objects
            var that=obj,
                triggerChoice = document.getElementById(that.id),
                domChoice1 = document.getElementById("Choice1"),
                domChoice2 = document.getElementById("Choice2");
            // Apply
            if (triggerChoice.checked && triggerChoice.id === "Choice1") 
                domChoice2.checked=false;
            if (triggerChoice.checked && triggerChoice.id === "Choice2") 
                domChoice1.checked=false;
            // Logout
            var log = document.getElementById("message");
            log.innerHTML += "<br>"+ (domChoice1.checked ? "1" : "0") + ":" + (domChoice2.checked ? "1" : "0");
            // Return !
            return that.checked;
        }
    </script>
</head>
<body>
    <h1 id="title">Title</h1>
    <label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice1" />Choice #1</label> 
    <label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice2" />Choice #2</label>
    <hr>
    <div id="message"></div>
</body>
</html>

0
投票

试试这个

<form id="form" action="#">
            <input name="checkbox1" type="checkbox" />
            <input name="checkbox2" type="checkbox" />
            <input name="checkbox3" type="checkbox" />
            <input name="checkbox4" type="checkbox" />
            <input name="checkbox5" type="checkbox" />
            <input name="checkbox6" type="checkbox" />
            <input name="checkbox7" type="checkbox" />
            <input name="checkbox8" type="checkbox" />
            <input name="checkbox9" type="checkbox" />
            <input name="checkbox10" type="checkbox" />
            <input type="submit" name="submit" value="submit"/>
        </form>

这是javascript

(function () {
    function checkLikeRadio(tag) {
        var form = document.getElementById(tag);//selecting the form ID 
        var checkboxList = form.getElementsByTagName("input");//selecting all checkbox of that form who will behave like radio button
        for (var i = 0; i < checkboxList.length; i++) {//loop thorough every checkbox and set there value false. 
            if (checkboxList[i].type == "checkbox") {
                checkboxList[i].checked = false;
            }
            checkboxList[i].onclick = function () {
                checkLikeRadio(tag);//recursively calling the same function again to uncheck all checkbox
                checkBoxName(this);// passing the location of selected checkbox to another function. 
            };
        }
    }

    function checkBoxName(id) {
        return id.checked = true;// selecting the selected checkbox and maiking its value true; 
    }
    window.onload = function () {
        checkLikeRadio("form");
    };
})();
© www.soinside.com 2019 - 2024. All rights reserved.