Ashwin B Chandrappa
Ashwin B Chandrappa

Reputation: 11

Click on dynamically generated radio button

i am trying to alert some text when a dynamically generated radio button is checked .. here is the link from fiddle .. http://jsfiddle.net/z7cu3q0y/

function createRadioButtons(n)
{
    $("#radioContainer").empty();
    for(var i=0;i<n;i++)
    {
        radioButtons = "<p><input type='radio' class='"+n+"' name='"+n+"'>"+(i+1)+"</p>";
        $("#radioContainer").append(radioButtons);
    }
}    

$("#dropDown").on("change",function()
{
      createRadioButtons(parseInt($(this).val()));
});

$("#radioContainer input").on("change",function()
{
      alert("checked");
});

when i click on radio button i am not getting alert .. can any one of you please help me in taking a look ?

Thanks in advance, Ashwin

Upvotes: 1

Views: 2978

Answers (4)

T J
T J

Reputation: 43156

Your code $("#radioContainer input").on("change",function(){}) will directly attach the event handler to the matching elements that are currently present in DOM.

To work with dynamically generated elements added in the future, You need to delegate your event handler to a common parent element:

$("#radioContainer").on("change","input",function(){
  alert("checked");
});

The above will attach the handler to #radioContainer, Whenever the corresponding event (change in this case)is triggered (Usually propagated from the children), it checks whether the event target matches the specified selector (input in this case) and invokes the handler accordingly.

Updated Fiddle

Upvotes: 8

Iago
Iago

Reputation: 1214

You need to put the input defined as click area and radiocontainer as working area.

DEMO: http://jsfiddle.net/don/z7cu3q0y/3/

Just remove input before .on and put inside of the function.


jQuery:

function createRadioButtons(n)
{
    $("#radioContainer").empty();
    for(var i=0;i<n;i++)
    {
        radioButtons = "<p><input type='radio' class='"+n+"' name='"+n+"'>"+(i+1)+"</p>";
        $("#radioContainer").append(radioButtons);
    }
}    

$("#dropDown").on("change",function()
{
      createRadioButtons(parseInt($(this).val()));
});

$("#radioContainer").on("change", 'input', function()
                              {
                                  alert("checked");
                              });

Upvotes: 0

karan3112
karan3112

Reputation: 1867

Try using the below code

$(document).on("change","#radioContainer input",function(){
 alert("checked");
});

Updated fiddle

Upvotes: 0

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

You need to use .on() for dynamically generated elements like below. Here .on() will bind change event to all radio buttons which are inside radioContainer

$("#radioContainer").on("change","input[type=radio]",function()
{
      alert("checked");
});

Demo

Upvotes: 2

Related Questions