Jquery-Dynamic Radio Buttons
Solution 1:
element
's value can't be duplicated in the HTML.
You need to define element
inside the loop, or, since I don't see any use of defining the radios into a variable you can simply do:
$("#choice").change(function(){
$( '#reports' ).empty();
var radio_name=$("#choice option:selected").text();
var a=$("#choice option:selected").val();
for(i=1;i <= a;i++)
$( '<input type="radio" name='+ radio_name +'/><br>' ).prependTo('#reports');
});
empty()
is used to clear the container.
Solution 2:
Try with the following:
$(document).ready(function(){
$("#choice").change(function(){
var radio_name=$(this).text();
var element=$('<input type="radio" name='+ radio_name +'/><br>');
element.appendTo('#reports');
});
});
- Get selected item text
- Create new radio element using selected item text
- Append new element to reports div
Best Regards,
Solution 3:
I saw a few tweaks, like the name needs a [] to make it part of an array. And I think them main problem was that the element object being created was being reused when a new object needed to be created every time.
I tested on jsFiddle to make sure jsFiddle
$(document).ready(function(){
$("#choice").change(function(){
var radio_name=$("#choice option:selected").text();
var a=$("#choice option:selected").val();
for(i=1;i <= a;i++){
$('<input type="radio" name="'+radio_name+'[]" /><br>').prependTo('#reports');
}
});
});
Solution 4:
In your for statement you start with i=1;
and you tell the function to run until i <= a
.
It doesn't matter what positive integer you set the value of a
to be it will always be at least equal to if not more than i
. So you're only appending once.
Post a Comment for "Jquery-Dynamic Radio Buttons"