1

I am basically trying to build a simple quiz game to learn JavaScript. How do I make the radio buttons not have on option selected when the next question is displayed?

See JSFiddle example here

I tried something like this but this is JQuery.

$('[name="ans"]').prop('checked', false); 
HattrickNZ
  • 4,373
  • 15
  • 54
  • 98

2 Answers2

2

If you're sure that your users are using up-to-date browsers, which support the DOM document.querySelector() method, you can use:

document.querySelector('input[type="radio"]:checked').checked = false;

JS Fiddle demo.

The benefit of querySelector() is that it returns only the first element that matches the selector pattern (assuming it matches any element) (though if you want to get all the matching elements there's document.querySelectorAll()).

The document can, of course, be replaced with am element-node reference (to restrict the method to searching only the form, for example, rather than the whole document).

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
1

If you really want to avoid using jQuery, you can try something like this:

var radios = document.getElementsByName('an');
for(i = 0; i < radios.length; i++){
    radios[i].checked = false;
}

JSFiddle Demo

Notice the second radio element is checked inside the HTML, but this code is executed on each nextQ() call

DarkAjax
  • 15,955
  • 11
  • 53
  • 65
  • would you reccommend Jquery over my current setup? It seems to me that Jquery might be a more efficient way to do this. but I am just learning...maybe the slow way using this current way with javascript/document.getElementById – HattrickNZ Jul 24 '13 at 22:34
  • Stick with vanilla JS. You'll end up with a better perspective of browsers and their differences. If you want to be a little more efficient in your code, you could change your data structure a bit and store off any dom elements you'll be accessing once on initialization, then just loop through them. Also, introduce some CSS and let it do some of the work for you. [JSFiddle Demo](http://jsfiddle.net/ZMqVT/16/) – dc5 Jul 25 '13 at 00:10
  • @HattrickNZ Sometimes using jQuery is good for compatibility but using plain JavaScript tends to be more efficient... – DarkAjax Jul 25 '13 at 00:34
  • @dc5 Thanks very much for that. I am ownly learning and know that there is lots of better ways of doing this. so thanks for the example to refer to!! – HattrickNZ Jul 25 '13 at 20:42
  • 1
    @dc5 these links help me understand your code a bit more how you hide and unhide stuff [link1](http://jsfiddle.net/NrGgA/) [link2](http://jsfiddle.net/6A7Lt/) – HattrickNZ Jul 26 '13 at 00:36