Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery, what is the best way to set onClick event listeners for radio buttons?

For the following HTML:

<form name="myForm">
    <label>One<input  name="area"  type="radio" value="S"  /></label>
    <label>Two<input name="area"   type="radio" value="R" /></label>
    <label>Three<input name="area"   type="radio" value="O" /></label>
    <label>Four<input name="area" type="radio" value="U" /></label>
</form>

Changing from the following JavaScript code:

$(function() {
     var myForm = document.myForm;
     var radios = myForm.area;
     
     // Loop through radio buttons
     for (var i=0; i<radios.length; i++) {
        if (radios[i].value == "S") {
            radios[i].checked = true;   // Selected when form displays
            radioClicks();   // Execute the function, initial setup
        }
        radios[i].onclick = radioClicks;  // Assign to run when clicked
     }  
 });

Thanks

EDIT: The response I selected answers the question I asked, however I like the answer that uses bind() because it also shows how to distinguish the group of radio buttons

like image 789
Jay Corbett Avatar asked Sep 05 '08 19:09

Jay Corbett


People also ask

Does Onclick work with radio buttons?

You can select any radio button either by clicking on the label or by clicking on the radio button. Radio button onclick You can trigger an event to know which radio button is checked. For this select all radio buttons and add an onclick event to all button.

What is the event for radio button?

A radio button fires the change event after you select it. How it works: First, register an event handler to the change event of the body . When a radio button is clicked, its change event is bubbled to the body.

Is radio checked in jQuery?

We can check the status of a radio button by using the :checked jQuery selector together with the jQuery function is . For example: $('#el').is(':checked') . It is exactly the same method we use to check when a checkbox is checked using jQuery.


2 Answers

$(document).ready(function(){
    $("input[name='area']").bind("click", radioClicks);
});

functionradioClicks() {
    alert($(this).val());
}

I like to use bind() instead of directly wiring the event handler because you can pass additional data to the event hander (not shown here but the data is a third bind() argument) and because you can easily unbind it (and you can bind and unbind by group--see the jQuery docs).

http://docs.jquery.com/Events/bind#typedatafn

like image 187
rp. Avatar answered Nov 09 '22 22:11

rp.


$( function() {
    $("input:radio")
        .click(radioClicks)
        .filter("[value='S']")
        .attr("checked", "checked");
});
like image 39
Juan Avatar answered Nov 10 '22 00:11

Juan