最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check box with radiobutton functionality - Stack Overflow

programmeradmin0浏览0评论
<style>
    .chb
    {
        width: 30px;
    }
</style>

<script type="text/javascript" src="jquery-1.5.2.js"></script>
<script>
    $(".chb").each(function() {
        $(this).change(function() {
            $(".chb").attr('checked',false);
            $(this).attr('checked',true);
        });
    });
</script>

<form action="demo_form.asp">
    <input type="checkbox" name="vehicle" value="Bike" class ="chb"> I have a bike<br>
    <input type="checkbox" name="vehicle" value="Car" checked="checked" class="chb"> I have a car <br>
</form>

The above coding contains two check boxes with radio button functionality. This works fine. But how to do this with javascript without using the jquery. How to achieve this.

<style>
    .chb
    {
        width: 30px;
    }
</style>

<script type="text/javascript" src="jquery-1.5.2.js"></script>
<script>
    $(".chb").each(function() {
        $(this).change(function() {
            $(".chb").attr('checked',false);
            $(this).attr('checked',true);
        });
    });
</script>

<form action="demo_form.asp">
    <input type="checkbox" name="vehicle" value="Bike" class ="chb"> I have a bike<br>
    <input type="checkbox" name="vehicle" value="Car" checked="checked" class="chb"> I have a car <br>
</form>

The above coding contains two check boxes with radio button functionality. This works fine. But how to do this with javascript without using the jquery. How to achieve this.

Share Improve this question edited Nov 24, 2012 at 5:42 arulmr 8,8469 gold badges56 silver badges70 bronze badges asked Nov 24, 2012 at 5:05 RithuRithu 1,2893 gold badges19 silver badges38 bronze badges 6
  • 3 Why not just use radiobuttons? – Sidharth Mudgal Commented Nov 24, 2012 at 5:07
  • 1 Semantically you should be using radio buttons. – rink.attendant.6 Commented Nov 24, 2012 at 5:09
  • 1 The client wants to use check box with radio button functionality without include jquery – Rithu Commented Nov 24, 2012 at 5:10
  • 2 it's back to document.getElementById but I'm not writing it out - I might burst into flames. – Popnoodles Commented Nov 24, 2012 at 5:14
  • possible duplicate stackoverflow./questions/13505747/… – suresh gopal Commented Nov 24, 2012 at 5:46
 |  Show 1 more ment

5 Answers 5

Reset to default 4

If you concern only about functionality and you have lot of checkboxes this is an easy solution.

<script>
    function func(checkBox) {
        var inputs = document.getElementsByTagName("input");
        for(var j = 0; j < inputs.length; j++) {
          if(inputs[j].type == "checkbox" && (inputs[j].className == "chb")){
             inputs[j].checked = false;
          }     
        }
        checkBox.checked = true;
    }
</script>

Now add onclick events to your all checkboxes as below.

<input type="checkbox" name="vehicle" value="Bike" class ="chb" onclick="func(this);"> I have a bike<br>
<input type="checkbox" name="vehicle" value="Car" checked="checked" class="chb" onclick="func(this);"> I have a car <br>

Maybe, you can have your cake and eat it too. If this is just about looks and you are open to consider a CSS solution, you can have radio buttons in the code, and make it look like they are checkbox.

input[type="radio"] {
    -webkit-appearance: checkbox;
    -moz-appearance: checkbox;
}​ 

No javascript or jQuery needed. However, I have not tested how cross-browser friendly this is. Definitely works on Chrome and Firefox. Definitely does NOT work on IE

I'm assuming that you only need this functionality for inputs with the class name chb. Otherwise even more loops will be required.

Unlike the other solutions mentioned here, my code doesn't require adding onclick to every checkbox:

<!DOCTYPE html>
<html lang="en-CA">
<head>
    <meta charset="utf-8">
    <title> My page </title>
    <script>
    function doCrazyCheckRadioThing(v) {
        var checkboxes, i;

        for(i=0, checkboxes = document.getElementsByClassName('chb'); i<checkboxes.length; i+=1) {
            checkboxes[i].checked = (checkboxes[i].value === v);
        }
    }

    function init() {
        var checkboxes, i;

        for(i=0, checkboxes = document.getElementsByClassName('chb'); i<checkboxes.length; i+=1) {
            checkboxes[i].addEventListener('change', function() {
                doCrazyCheckRadioThing(this.value);
            }, false);
        }
    }

    document.addEventListener('DOMContentLoaded', init, false); 
    </script>
<body>
    <form action="demo_form.asp">
        <input type="checkbox" name="vehicle" id='bike' value="Bike" class="chb"> I have a bike<br>
        <input type="checkbox" name="vehicle" id='car' value="Car" checked="checked" class="chb"> I have a car <br>
    </form>

Again I must stress that is a very non-semantical way of coding HTML to do this.

Details: Probably not the most elegant of code but it will do the trick and will give you ideas on how to customise it for your purpose

<input type="checkbox" name="chkFirst" onclick="CheckboxCheck('first')" />
<input type="checkbox" name="chkSecond" onclick="CheckboxCheck('second')" />

<script>
    function CheckboxCheck(checkbox)
    {
        var firstCheckbox = document.getElementById('chkFirst');
        var secondCheckbox = document.getElementById('chkSecond');

        if (checkbox == "first")
        {
            if (secondCheckbox.checked && firstCheckbox.checked == true)
            {
                secondCheckbox.checked = false;
            }
        }
        else
        {
            if (firstCheckbox.checked && secondCheckbox.checked == true)
            {
                firstCheckbox.checked = false;
            }
        }
    }
</script>

Well @prageeth code works well and all but an optimization would be to just retrieve only the checkboxes in the very 1st line of code so that you would not have to check two things inside the loop, I guess this would save some performance time.

I even found a better way without even having to use any conditions inside the loop. This answer is edited..

<script>
    function func(checkBox) {
        var inputs = document.querySelectorAll("[type=checkbox], [class=chb]");
        for(var j = 0; j < inputs.length; j++) {
             inputs[j].checked = false;
        }
        checkBox.checked = true;
    }
</script>
发布评论

评论列表(0)

  1. 暂无评论