user1050619
user1050619

Reputation: 20916

Event delegation in Jquery

Im adding few radio buttons within a container dynamically using Jquery append method and added the event handler for all the radio buttons but its not working

Question:

Whenever I click the radio button within the container, I need a set of commands to be executed..

fiddle- http://jsfiddle.net/Z86kW/1/

Jquery

$(document).ready(function(){
    $('#container').append('<input type="radio" name="radio1"/>');
    $('#container').append('<input type="radio" name="radio2"/>');
    $('#container').append('<input type="radio" name="radio3"/>');


    $( "#container" ).on( "click", "radio", function( event ) {

            alert( $( this ).text() );
            })
})

css

#container{
    height:100px;
    width:200px;
    background-color:red;
}

html

<div id="container">

</div>

Upvotes: 0

Views: 56

Answers (3)

Ashok Kumar Gupta
Ashok Kumar Gupta

Reputation: 974

I have tweak the jquery code. refer this url http://jsfiddle.net/Z86kW/9/

PS: Also, keep the name value same to have only one radio selected at a time.

Cheers, Ashok

Upvotes: 0

Ishan Jain
Ishan Jain

Reputation: 8171

Here you want to select all elements of type radio then you must use :radio selector.

$("#container" ).on( "click", ":radio", function( event ) {
     alert( $( this ).text() );
});

Fiddle

or you can also use input[type=radio].

$("#container" ).on( "click", "input[type=radio]", function( event ) {
     alert( $( this ).text() );
});

Fiddle

Upvotes: 0

Satpal
Satpal

Reputation: 133453

Your selector is incorrect, You missed : with selector

$( "#container" ).on( "click", ":radio", function( event ) {

Fiddle DEMO

$(":radio") is equivalent to $("[type=radio]").

Upvotes: 3

Related Questions