Reputation: 1102
I am trying to do this.
I have 3 radio buttons,
I want to do in standard javascript without jquery as can't have that at the moment.
Here's my code so far.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<script type="text/javascript">
function toggle(radioBtn)
{
if(radioBtn.checked)
{
radioBtn.checked = false;
}
else
{
radioBtn.checked = true;
}
// only select one at a time.
}
</script>
</head>
<body>
<form id="myForm" name="myForm">
<input type="radio" name="radioBtn" id="radioBtn1" value="A" onClick="toggle(this);" />
<input type="radio" name="radioBtn" id="radioBtn1" value="B" onClick="toggle(this);"/>
<input type="radio" name="radioBtn" id="radioBtn1" value="C" onClick="toggle(this);"/>
</form>
</body>
</html>
Please help. Your help will be appreciated. Thanks
Upvotes: 0
Views: 26327
Reputation: 1231
This might not be a solution which will go into the book for being clean but i got it working.
HTML:
<input type="radio" name="radioBtn" id="radioBtn1" value="A" onmouseup="toggle(this);"/>
<input type="radio" name="radioBtn" id="radioBtn2" value="A" onmouseup="toggle(this);" />
<input type="radio" name="radioBtn" id="radioBtn3" value="A" onmouseup="toggle(this);"/>
Javascript:
function toggle(radioBtn)
{
if(radioBtn.checked)
{
setTimeout("disableRadio('"+radioBtn.id+"')",10);
} else {
radioBtn.checked = true;
}
}
function disableRadio(radioId) {
el = window.document.getElementById(radioId);
el.checked = false;
}
Your code wasn't working because the javascript setter gets overruled by html click events or something. I don't know how to explain it the correct way but having a delay solves your problem.
Hope this helps out!
Upvotes: 0
Reputation: 5227
You can get around the browser's default behavior for radio buttons and achieve the toggle effect you're after by creating an additional 'hidden' radio button, and simulating a click
event for it when the user toggles off one of the visible buttons. See a working example in this jsFiddle: http://jsfiddle.net/k73Nt/
Upvotes: 0
Reputation: 3247
You could just do something simple and straight forward inline, like this:
<input type="radio" name="radioBtn" id="radioBtn1" value="A" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false" />
<input type="radio" name="radioBtn" id="radioBtn2" value="B" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false"/>
<input type="radio" name="radioBtn" id="radioBtn3" value="C" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false"/>
Upvotes: 8
Reputation: 16905
Keep a record of which radioButton is checked and which isn't (can be done with hidden fields or an array) and set the checked/unchecked accordinally
Upvotes: 0