make checkbox behave like radio buttons with javascript

Solution 1:

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

if you want user can unchecked selected item :

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

Demo :

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

Solution 2:

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

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.

Solution 3:

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>

Solution 4:

This is a better option as it allows unchecking also:

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