Arif YILMAZ
Arif YILMAZ

Reputation: 5866

Jquery Cannot find dynamically created radiobuttons

I am trying have a list of radiobuttons and when user click one of it, I want to Alert("Warning message") .

I have a static radiobutton created and if I click on it, I can see the Alert() box. But If I click the dynamically created radio button, Alert() doesnt show up.

here is the static radiobutton, This triggers the Alert()

<input type="radio" class="radio_profile" name="radio_profile" id="radio_profile_not_found" value="0">

here is the one created in webmethod, this doesnt trigger Alert()

 rtn_str = "<input type='radio' class='radio_profile' name='radio_profile' id='radio_profile_" + dr["ProfessionalID"].ToString() + "' value='" + dr["ProfessionalID"].ToString() + "' >"

here is the Jquery Code

$("input[name='radio_profile']").change(function () {
     alert('Warning Message');
});

Would you please help me fix dynamically created radiobuttons to trigger Alert() box

Upvotes: 0

Views: 269

Answers (4)

Karan
Karan

Reputation: 3328

In asp.net, you can stick the property ClientIDMode="Static" to the radionbutton control. This way you would be able to use the control id as specified in the page. You can also do the event handling based on the control ID also.

Upvotes: 0

sasi
sasi

Reputation: 4318

$(document).on("change",'input[name="radio_profile"]',function(){
 alert('Warning Message');
});

Upvotes: 0

Anthony Grist
Anthony Grist

Reputation: 38345

You need to use event delegation with the .on() function:

$(document).on('change', 'input[name="radio_profile"]', function(e) {
    alert('Warning Message');
});

Ideally, rather than document, you'd call .on() after selecting a static (exists when the page loads) element that will contain all of your dynamically added radio buttons. The closer the static element is to them the better. Without seeing the HTML of the page it's difficult to know what element that should be though.

Upvotes: 4

Gary Stevens
Gary Stevens

Reputation: 693

The change() event will be bound to all elements matching the selector when the function runs. It doesn't know about new elements. You'll ether have to run the function to rebind the event handler again - or use on('change', function(){.

The JQuery docs explain more: http://api.jquery.com/on/

Upvotes: 0

Related Questions