Quite often, I find myself in a situation where I need to change the content of a form based on which checkboxes or radio buttons in a group are checked. I used to do this by adding an onclick and/or onchange event to each individual checkbox or radio button and then running a function to figure out whether or not the changed element was checked.
Then, I discovered how easy it is to do all of this on-the-fly with jQuery.
To begin with, let’s say we have a group of radio buttons inside of a fieldset with the ID of “myRadioGroup.” We can easily use jQuery to iterate through each radio button and see if it’s checked or not, then take action based on those results.
$(document).ready(
function() {
$('#myRadioGroup input[type=radio]').click(
function() {
// Call a function onclick of the radio button
}
);
$('#myRadioGroup input[type=radio]').each(
function() {
if($(this).is(':checked')) {
// Do some stuff if it's checked
alert('The radio button with a value of '+$(this).val()+' is checked');
} else {
// Do some other stuff if it's not
alert('The radio button with a value of '+$(this).val()+' is not checked');
}
}
);
}
);
The function above will wait until the document is loaded. Then, it will search the myRadioGroup fieldset (or div or whatever type of HTML element to which you assigned that ID) for any radio inputs. First, I’ve set it up to add an onclick event handler to all of those radio buttons. Then, I’ve set it up to iterate through the collection of radio buttons and figure out whether or not each one is checked.
In my example, an alert box will pop up for each radio button providing the value of the radio button and telling you whether or not it’s checked.
I’m sure there’s probably a way to chain the two functions together, but each attempt I made at doing so thus far has failed.
You can also take the basic code for figuring out whether or not the radio button is checked and performing various actions based on that information out of the jQuery statement and create an external function out of it. That way, you can even call it from your onclick event handler. That takes a little more configuration (you have to pass the “this” parameter to your external function), but it’s definitely doable.
When looking for this solution initially, I came across a post in the Drupal developer docs, which is where I got the idea for this post.
Post Your Comment