Search the Community
Showing results for tags 'ch10'.
-
Hello Guys, I have been going over the book and wanted to do small exercise..., where I have form with three radio buttons and when clicking each one I am alerted (alert() method) with the value of the radio button. HTML markup looks like: <form action="#" method="post" id="theForm"> <fieldset><legend>Select Radio Button</legend> <div> <p> <input type="radio" name="options" id="a1" value="a1"> a1 <input type="radio" name="options" id="b2" value="b2"> b2 <input type="radio" name="options" id="c3" value="c3"> c3 </p> </div> <div> <p id="res"></p> </div> <input type="submit" value="Submit" id="submit"> </fieldset> </form> JavaScript Code: window.onload = function () { 'use strict'; document.getElementsByName('options').onchange = displaySelection; //document.getElementById('a1').onclick = displaySelection; //document.getElementById('b2').onclick = displaySelection; //document.getElementById('c3').onclick = displaySelection; }; function displaySelection() { 'use strict'; var selection = document.getElementsByName('options'); var result; for (var i = 0, count = selection.length; i < count; i++) { if (selection[i].checked) { result = selection[i].value; alert(result); break; } } } It works perfectly when using onclick event with reference to the id (three lines commented at the beginning) but it does not work when I refere to the element by name… with event onchange or onclick. Can you guys explain why is that? Thanks, Tom
- 2 replies
-
- ch10
- radio buttons
-
(and 2 more)
Tagged with: