A little bit of playing with Javascript and Jquery for a client, I thought it was worth documenting a nice piece of Javscript, which can find which of the radio buttons is selected, and assign it’s value to a variable. The reason I like it, is that it is much simpler than the equivalent pure javascript. So for the radio buttons below in a form;

jquery-featured-image

<input name="mic" type="radio" value="Mic 1" /> Mic 1
<input name="mic" type="radio" value="Mic 2" /> Mic 2
<input name="mic" type="radio" value="Mic 3" /> Mic 3

You can use this code to populate the value of the selected radio button into a variable called micNumberText;

<script>
var micNumberText = "";
$('input[name="mic"]').each(function () {
if($(this).attr('checked')) {
micNumberText = $(this).attr('value');
}
});
</script>

I like it because Jquery allows you to select the inputs with the name “mic” very easily as you can see above, and then you can use .each and run an anonymous function on each of the radio buttons. And to refer to the radio button in question all you do is use $(this), I like JQuery, but usually find myself amending existing Jquery code rather than writing it myself from scratch, I enjoyed this experience and will be using it more.

For interest here is the code in Javascript which does the same as what the Jquery is doing;

<script>
var micNumberText = "";
var radios = document.getElementsByName('mic');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
micNumberText = radios[i].value;
}
}
</script>

It’s somewhat more complicated I guess, whereas the Jquery is much simpler and more succinct.

Share this via:


SOCIAL MEDIA


Copyright © 2019 Digital Technology Labs Limited (Company No: 11577499) | Terms  | PrivacyCookies | Areas served
Web design Langdon Hills | Web design Basildon | Web design Essex