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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5839884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:08:51  来源:igfitidea点击:

make checkbox behave like radio buttons with javascript

javascripthtml

提问by Christian

I need to manipulate the behavior of the check boxes with javascript. They should basically behave like radio buttons (only one selectable at a time, plus unselect any previous selections).

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

The problem is that I can't use plain radio buttons in first place, because the name attribute for each radio button would be different.

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

I knowits not the ultimate and shiniest solutions to make an apple look like a pear, and w3c wouldn't give me their thumbs for it, but it would be a better solution right now than to change the core php logic of the entire cms structure ;-)

我知道这不是让苹果看起来像梨的终极和最闪亮的解决方案,w3c 不会给我他们的拇指,但现在这将是一个更好的解决方案,而不是改变整个 cms 的核心 php 逻辑结构体 ;-)

Any help is much appreciated!

任何帮助深表感谢!

回答by DJafari

HTML :

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 :

jQuery :

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

if you want user can unchecked selected item :

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

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

Demo :

演示:

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

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

回答by Vaibhav Garg

This is a better option as it allows unchecking also:

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

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

回答by KooiInc

There are many ways to do this. This is a clickhandler (plain js) for a div containing a number of checkboxes:

有很多方法可以做到这一点。这是一个包含多个复选框的 div的点击处理程序(纯 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;
        }
    }
}

Here's a working example.

这是一个工作示例

回答by Luc Eeckelaert

I kept it simple...

我保持简单...

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

回答by GordonM

You could give the group of checkboxes you need to behave like this a common class, then use the class to attach the following event handler:

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

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

Note: This is pretty me just shooting from the hip, I've not tested this and it might need tweaking to work.

注意:这很漂亮,我只是从臀部拍摄,我没有测试过,它可能需要调整才能工作。

I would advise that you do look into finding a way of doing this with radio buttons if you can, as radios are the proper tool for the job. Users expect checkboxes to behave like checkboxes, not radios, and if they turn javascript off they can force through input into the server side script that you weren't expecting.

如果可以的话,我建议您确实考虑寻找一种使用单选按钮执行此操作的方法,因为收音机是完成这项工作的合适工具。用户希望复选框的行为像复选框,而不是收音机,如果他们关闭 javascript,他们可以强制通过输入到您不期望的服务器端脚本中。

EDIT: Fixed function so that uncheck works properly and added a JS Fiddle link.

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

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

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

回答by Jamshaid Kamran

Just in case it helps someone else

以防万一它帮助别人

I was having the same situation where my client needed to have a checkboxbehaving like a radio button. But to me it was meaningless to use a checkboxand make it act like radio buttonand it was very complex for me as I was using so many checkboxesin a GridViewControl.

我遇到了同样的情况,我的客户需要checkboxradio button. 但对我来说,使用 acheckbox并让它表现得像这样毫无意义,radio button而且这对我来说非常复杂,因为我checkboxesGridViewControl 中使用了这么多。

My Solution:
So, I styled a radio buttonlook like a checkboxand took the help of groupingof radio buttons.

我的解决方案:
所以,我设计了一个radio button类似 a 的样式checkbox并借助grouping了单选按钮。

回答by mapetek

@DJafari's answer doesn't let unchecking the checkbox. So I've updated it like this:

@DJafari 的回答不允许取消选中复选框。所以我更新了它:

$(".chb").change(function(e) {

 //Getting status before unchecking all
  var status = $(this).prop("checked");

  $(".chb").prop('checked', false);
  $(this).prop('checked', true);

 //false means checkbox was checked and became unchecked on change event, so let it stay unchecked
  if (status === false) {
    $(this).prop('checked', false);
  }

});

https://jsfiddle.net/mapetek/nLtb0q1e/4/

https://jsfiddle.net/mapetek/nLtb0q1e/4/

回答by robx

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

Ultimately you can use brackets with the name attribute to create an array of radio input like so:

最终,您可以使用带有 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

What matters to transfer in the end are whats in the value attribute. Your names do not have to be different at all for each radio button. Hope that helps.

最终要传递的是 value 属性中的内容。每个单选按钮的名称不必完全不同。希望有帮助。

回答by vincedgy

In Simple JS. Enjoy !

在简单的 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>

回答by mitul

try this

尝试这个

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

and this is the javascript

这是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");
    };
})();