eggster34
asked on
mutually exclusive checkboxes (not radio buttons.)
Hi there, I need to create a form where there are 2 checkboxes, one says YES and the other says NO, and only one of them should be selectable at any one time. How can I achieve this? I know this works with radio buttons , but I'm not sure how it can be done by chekboxes instead?
use radio button instead
<input type=radio name=rgOpt value="1"> A
<input type=radio name=rgOpt value="2"> B
<input type=radio name=rgOpt value="1"> A
<input type=radio name=rgOpt value="2"> B
You could make your second checkbox checked value equal not the first checkbox checked value.
if you insist on checkbox here it is
<input type=radio name=rgOpt value="1"> A
<input type=radio name=rgOpt value="2"> B
<hr>
<input type=checkbox id=chkA name=chkA value="1" onclick="chk(this)"> A
<input type=checkbox id=chkB name=chkB value="2" onclick="chk(this)"> B
<script>
function chk(c) {
if (c.name == 'chkA') document.getElementById('chkB').checked = (!c.checked);
if (c.name == 'chkB') document.getElementById('chkA').checked = (!c.checked);
}
</script>
Just use a simple javascript function triggered onClick of the checkbox to mimic a radio button. Both checkboxes should have the same name but different id's.
function oneCheck(name,id)
{
var y = document.getElementById(id);
if (y.checked == true)
{
var x=document.getElementsByName(name);
for(var n=0;n<x.length;n++)
{
x[n].checked=false;
}
y.checked = true;
}
Then the HTML for the checkboxes:
<input type="checkbox" name="boxname" id="box1" value="yes" onClick="oneCheck(this.name,this.id);">
<input type="checkbox" name="boxname" id="box2" value="no" onClick="oneCheck(this.name,this.id);">
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
jQuery solution:
<script src="http://code.jquery.com/jquery-1.4.2.js"></script>
<input type="checkbox" name="chkYN" value="Yes"> YES
<input type="checkbox" name="chkYN" value="No"> NO
<script>
$('document').ready( function () {
$(':checkbox[name="chkYN"]').click( function () {
$(':checkbox[name="chkYN"]:checked').not(this).attr('checked', false);
});
});
</script>
<script type="text/javascript">
$("#checkbox1").click( function() { $("#checkbox2").attr("chec
$("#checkbox2").click( function() { $("#checkbox1").attr("chec
</script>
<input type="checkbox" id="checkbox1">
<input type="checkbox" id="checkbox2">
Of course, if you don't have jquery, you'll have to use rudimentary standard JS + DOM:
var x = document.getElementById("c
x.setAttribute("checked", false);
-OR-
<input type="checkbox" id="checkbox1" onclick="document.getEleme
etc...