Log in

View Full Version : How do you attach an event listener to radio button using javascript



andreea115
07-16-2013, 08:58 AM
Hello everyone.

i am fairly new to javascript and having problems attaching an event listener to a radio button .

i am trying to get the values from a clicked radio button so that i can then attach those values to a javascript enclode64. but i don't seem to be able to attach to the event.

it might be easier if i show u what i have done so far;

The HTML radio button tag: They are NOT enclosed within a form


<input class="link-selector-flash" type="radio" name="link-type" id="link-type-template" data-url-base="www.sample.url1" />

<input class="link-selector-flash" type="radio" name="link-type" id="link-type-template" data-url-base="www.sample.url2" />

<input class="link-selector-flash" type="radio" name="link-type" id="link-type-bespoke" data-url-base="www.sample.url2" />

the javacript code

window.onload = function(){

document.getElementsByName('link-type').onclick = function(){
alert('it works link name');

var radioButtons = document.getElementsByName("link-type");
for (var i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {

var thevalue = radioButtons[i].value;

document.getElementById('str64').value = Base64.encode(thevalue);
}
}
}


you will note that i tried to place the returned value in a Base64 encode ( i have not enclosed the javacript code for the encoder as this has been separately tested and it works perfectly.

the imput bar that i tried to transfer it to is listed below .


<input type="text" name="str64" id="str64" size="34" />

The code fell apart because i don't seem to be able to attach the right event to the listener. i.e to listen for the click of the radio button.

warm regards

Andreea

clueful
07-16-2013, 12:34 PM
Eliminate the onload handler by putting this at the end of the document:


(function()
{
var radioButtons = document.getElementsByName("link-type");

for ( var i = 0; radioButtons[ i ]; i++ )
radioButtons[ i ].onclick = f;

function f()
{
document.getElementById('str64').value = Base64.encode( this.value );
}
})()

jscheuer1
07-16-2013, 02:53 PM
Only real problem there is that those radio buttons have no values.

I kind of cringe a little though when I see a for loop where a while loop would work, also when I see i++ when ++i would work. These are just efficiencies though and don't matter with such a small amount of items to check. Limiting the loop by the existence of the element will fail in some older Mozilla script engines. Again, a fine point. Best to use the number:


var i = -1, limit = radioButtons.length;
while(++i < limit) radioButtons[ i ].onclick = f;

Going backwards is even more efficient if feasible - it is in this case:


var i = radioButtons.length;
while(--i > -1) radioButtons[ i ].onclick = f;

All fine points. But the killer is that those radios have no values.

andreea115
07-16-2013, 03:19 PM
Hello jscheuer1's and cluefu

thank you so much for your time taken to answer this question. Indeed, i think i just experienced the problem echoed by Jscheuer1. i just spent the last 30 mins trying to alert the values from the radio button, but to no avail.

Indeed, the radio buttons should have some values. it is these values i am trying to transfer .

if you look at my radio button, you will see that the values are contained within the : data-url-base. i.e

data-url-base="www.sample.url2"

it is these values that i need to collect and tranfer each time the radio button is clicked

i tried the following to echo the values


(function()
{
var radioButtons = document.getElementsByName("link-type");

for ( var i = 0; radioButtons[ i ]; i++ )
{
radioButtons[ i ].onclick = f;

}
function f()
{ alert( radioButtons[ i ] );
document.getElementById('str64').value = Base64.encode( this.value );

}
})()



So , i guess the question is this; how do i do it so that i can incorporate into the function a method to get the values from data-url-base

warm regards

Andreea

jscheuer1
07-16-2013, 03:40 PM
You would need AJAX for that. jQuery is the easiest method. But I'm curious how much unencoded data is in those files. The only Base64.encode javascript function I've ever seen cannot handle a lot of unencoded data unless it's already UTF-8 only characters anyway.

But lets just assume all that is OK for now, then:


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($){
$('input[name="link-type"]').click(function(){
$.ajax({
url: this.getAttribute('data-url-base'),
cache: false,
success: function(result){
$('#str64').val(Base64.encode(result));
}
});
});
});
</script>



should be the only script code you need.

If you want more help, please include a link to the page on your site that contains the problematic code so we can check it out.

andreea115
07-16-2013, 03:41 PM
i thought i should just mentioned that the value for the radio button have to be placed like this;


data-url-base="www.sample.url2"

The data-url-base is tied to another script that utilizes these values

jscheuer1
07-16-2013, 03:57 PM
Which other script? The Base64 script, specifically its Base64.encode() function? That's sort of how you have it written. If so, we could forget the jQuery and do:


<script type="text/javascript">
(function(){
function f(){
document.getElementById('str64').value = Base64.encode(this.getAttribute('data-url-base'));
}
var radioButtons = document.getElementsByName("link-type"), i = radioButtons.length;
while(--i > -1) radioButtons[ i ].onclick = f;
})();
</script>

Put that before the closing </body> tag.

If you want more help, please include a link to the page on your site that contains the problematic code so we can check it out.

jscheuer1
07-16-2013, 04:09 PM
Here's a working demo using webtoolkit.base64.js (from http://www.webtoolkit.info/javascript-base64.html):


<!DOCTYPE html>
<html>
<head>
<title>Button64 Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="webtoolkit.base64.js"></script>
</head>
<body>
<input class="link-selector-flash" type="radio" name="link-type" id="link-type-template" data-url-base="www.sample.url1" />

<input class="link-selector-flash" type="radio" name="link-type" id="link-type-template" data-url-base="www.sample.url2" />

<input class="link-selector-flash" type="radio" name="link-type" id="link-type-bespoke" data-url-base="www.sample.url2" /> <br>
<textarea id="str64" cols="50" rows="5" wrap="off"></textarea>
<script type="text/javascript">
(function(){
function f(){
document.getElementById('str64').value = Base64.encode(this.getAttribute('data-url-base'));
}
var radioButtons = document.getElementsByName("link-type"), i = radioButtons.length;
while(--i > -1) radioButtons[ i ].onclick = f;
})();
</script>
</body>
</html>

andreea115
07-16-2013, 04:27 PM
Hello again

one last question, when i tried to alert out the values from the returned results, it did not return the values in the radio button. but instead gave me a whole page of information. i have enclosed what i attempted to do below:


jQuery(function($){
$('input[name="link-type"]').click(function(){
$.ajax({
url: this.getAttribute('data-url-base'),
cache: false,
success: function(result){
alert(result);
$('#str64').val(Base64.encode(result));

}
});
});
});

what should i do?

warm regards

Andreea

jscheuer1
07-16-2013, 05:09 PM
What are you after, the url listed or the actual text? If it's the actual text, use the demo I just made up in my post:

http://www.dynamicdrive.com/forums/showthread.php?74477-How-do-you-attach-an-event-listener-to-radio-button-using-javascript&p=297247#post297247

clueful
07-17-2013, 09:20 PM
I kind of cringe a little though when I see a for loop where a while loop would work,
They compile identically and the for loop could be said to make its operation clearer.



also when I see i++ when ++i would work.When used as a for loop action I see no difference between them.


Limiting the loop by the existence of the element will fail in some older Mozilla script engines.Which don't exist due to the browser being self-updating.

jscheuer1
07-17-2013, 10:13 PM
Time trials prove that while and pre incrementing/decrementing are more efficient than for and post incrementing/decrementing. And that iterating from the last to the first is also more efficient than from first to last. Incidentally, in some cases it actually makes more logical sense to iterate backwards, like if you're removing items from an array or nodeList while iterating over it - if you go forwards, the iteration process loses track of the count.

However, both things I said - that it's a fine point and that with a small number of items to iterate over it makes little or no difference, apply here.

It's a good practice to get into though because you have no way to know for sure when the code you write will get applied in a situation where the number of items is great enough to warrant iterating over them in the most efficient manner possible.

About looping on existence - Those older Moz browsers are out there though, they were made before the self updating craze began. Self updating can easily be opted out of as well, and might need to be in certain environments.

However, I would agree that we are talking about a limited number of browsers, probably mostly on older computers - mostly owned by people/schools/other organizations with either limited financial means and/or limited knowledge of I.T. But I still like the idea of supporting folks like that, especially those of limited financial means, more so than the others, but them too.

andreea115
07-19-2013, 09:00 AM
thank you so much for your help on this matter. It worked.

warm regards

Andreea