goJson
goJson

Reputation: 223

how to make 'input.radio' to be not checked in if statements?

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;

Upvotes: 0

Views: 93

Answers (5)

exexzian
exexzian

Reputation: 7890

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" />

Upvotes: 1

StartCoding
StartCoding

Reputation: 393

change your html to this:

male<input type="radio" name="a" id="a"/>
<br/>
female<input type="radio" name="a" id="b"/>

Upvotes: 0

Alex Char
Alex Char

Reputation: 33218

You don't need js for this. Just set same name on both radios:

mail<input type="radio" name="test" id="a" />
<br/>
femail<input type="radio" name="test" id="b" />

fiddle

You need js for this only if you use this radio in an asp repeater.

Upvotes: 0

Peter
Peter

Reputation: 6669

Simplest case scenario, you shouldn't really require JavaScript to do the toggle if the "name" attribute of the checkboxes are the same.

<label>Male<input type="radio" id="a" name="gender"/></label>

<label>female<input type="radio" id="b" name="gender"/></label>

notice that i wrapped the checkboxes with label so that the text would be clickable as well.

Upvotes: 1

Deep
Deep

Reputation: 2512

<input type="radio" name="gender" value="male" />
<input type="radio" name="gender" value="female" />

And dont use javascript, Luke.

Upvotes: 0

Related Questions