fiddle : http://fiddle.jshell.net/12dkswgd/
I'm trying to choose a gender by elem 'input.radio'
So I made some if sentences, but it's not working.
I don't know why.
Belows are codes that I made. it's not working.
You can see more easier at fiddle : http://fiddle.jshell.net/12dkswgd/
html :
male<input type="radio" id="a"></input>
<br/>
female<input type="radio" id="b"></input>
js :
/* these sentences are not working
a = document.getElementById('a');
b = document.getElementById('b');
if(a.checked) {b.checked = false}
if(b.checked) {a.checked = false}
*/
/* these sentences are not working, either.
if(document.getElementById('a').checked) {
document.getElementById('b').checked = false
} else if(document.getElementById('b').checked) {
document.getElementById('a').checked = false
}
*/
/* this sentence is working. */
document.getElementById('a').checked = true;
Update 1: using onchange
handler - check fiddle
If you want to get it done using JavaScript then one way is like this fiddle:
Note: The problem with your JavaScript code was: you were not wrapping the JavaScript code inside any function ( so your code used to run only once ) and you need to handle the radio button click using a handler ( in fiddle its changeRadio('button')
and with bit more logic)
but as other people have suggested I would prefer HTML way which is more cleaner and simpler :
Male: <input type="radio" name="gender" value="male" />
Female: <input type="radio" name="gender" value="female" />