Jump to content
Larry Ullman's Book Forums

Ch10 Radio Buttons Example


Recommended Posts

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

Link to comment
Share on other sites

Hello and welcome to the forums, Tom.

 

document.getElementById returns a single DOM element, to which an event handler can be set up.

However, document.getElementsByName returns an array of DOM elements, and you cannot set up an event handler for an array of DOM element in the manner you are attempting to do so. If you want to set up an onclick/onchange event for an array of DOM elements, you need to loop through the array and set up an event handler for each one individually.

 

I hope that helps.

  • Upvote 1
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

×
×
  • Create New...