Asad Mahmood Asad Mahmood - 4 months ago 8
HTML Question

How to only have one checkbox checked at a time?

I want to figure out how to only have one

checkbox
checked at a time, I wish to do it with a function, and without
radio
s as that's not the style I am trying to go for.

My code is as follows :



function check(c01)
{
if((this).is(":checked") == true)
{
c02 = false;
}
}

<input type="checkbox" name="creditCheck" id="c01" value="Yes" onclick="check(c01);" />Yes
<input type="checkbox" name="creditCheck" id="c02" value="No" onclick= "check(c02);" />No'




Answer

Here is an example without JQuery. Add a class to your inputs.When Clicked, uncheck everything, and then check the clicked input if it was not checked.

    function check(input)
    {
    	
    	var checkboxes = document.getElementsByClassName("radioCheck");
    	
    	for(var i = 0; i < checkboxes.length; i++)
    	{
    		//uncheck all
    		if(checkboxes[i].checked == true)
    		{
    			checkboxes[i].checked = false;
    		}
    	}
    	
    	//set checked of clicked object
    	if(input.checked == true)
    	{
    		input.checked = false;
    	}
    	else
    	{
    		input.checked = true;
    	}	
    }
<input type="checkbox" class="radioCheck" name="creditCheck" id="c01" value="Yes" onclick="check(this);" />Yes     
<input type="checkbox" class="radioCheck" name="creditCheck" id="c02" value="No"  onclick= "check(this);" />No'