Reputation: 11286
Using jQuery, I'm dynamically generating radio buttons, however doing a "click-then-alert" check on each, only the first radio button responds (it's the original hardcoded one).
When using the script in my actual page, the selected radio button successfully passes to the server (any of them), so I know that each dynamically-created radio button is getting a value and passing it. In Firebug, each element is structured the same as the first hard-coded one.
Are dynamically created form elements not fully embedded in the DOM?
Perhaps the issue is with how I'm listening for a click, using 'this' or grabbing the 'value' ?
Sample code at JSFiddle: http://jsfiddle.net/2ny6c0hq/8
or...
HTML:
<script src="scripts/add_radio.js" language="Javascript" type="text/javascript"></script>
<div class="input_fields_wrapper">
Entry 1 <input class="radio_button" type="radio" name="correct_answer" value="answer_1" />
</div>
<div id="add_field">Add More Fields</div>
JAVASCRIPT (scripts/add_radio.js):
$(document).ready(function() {
var max_fields = 10; //maximum radio allowed
var wrapper = $(".input_fields_wrapper"); //Fields wrapper
var add_button = $("#add_field"); //Add button ID
var x = 1; // initial radio count
$(add_button).click(function(e){ // on add input button click
e.preventDefault();
if(x < max_fields){
x++; // increment counter
$(wrapper).append("<br />Entry " + x + " <input type='radio' class='radio_button' name='correct_answer' value='answer_" + x + "'>");
}
});
$(".radio_button").on("click", function(){
alert($(this).val());
});
});
Upvotes: 0
Views: 842
Reputation: 104775
You need to use event delegation for dynamic content handlers:
$(".input_fields_wrapper").on("click", ".radio_button", function() {
Upvotes: 1