Skip to content Skip to sidebar Skip to footer

Jquery-Dynamic Radio Buttons

I am trying to create radio buttons in a container. The total number of radio buttosn is supplied from the value selected in Combobox that is in another container, when I am trying

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');
     });

});
  1. Get selected item text
  2. Create new radio element using selected item text
  3. 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"