How to create a radio button dynamically with jQuery?

后端 未结 8 1034
南方客
南方客 2020-12-08 22:25

I am developing a small application in which I want to create 20 radio buttons in one row.

How can I do this using jQuery?

相关标签:
8条回答
  • 2020-12-08 22:35

    I think this will serve your purpose:

    for (i = 0; i < 20; i++) {
        var radioBtn = $('<input type="radio" name="rbtnCount" />');
        radioBtn.appendTo('#target');
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="target"></div>

    0 讨论(0)
  • 2020-12-08 22:36

    Something along the lines of:

    for (i = 0; i < 20; i++) {
        $('#element').append('<input type="radio" name="radio_name" />');
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="element"></div>

    0 讨论(0)
  • 2020-12-08 22:42

    Assuming that you have a div with the ID=myDivContainer try this:

    for (i=0;i<=20;i++)
    {
    $("#myDivContainer").append('<input type="radio" />')
    }
    
    0 讨论(0)
  • 2020-12-08 22:44

    You can do it with appendTo(), within a for loop:

    for (i = 0; i < 20; i++) {
        $('<input type="radio" name="dynradio" />').appendTo('.your_container');
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="your_container"></div>

    0 讨论(0)
  • 2020-12-08 22:45

    You have to find the element that should contain your radio buttons and append() them:

    var container = $('#radio_container');
    for (var i = 0; i < 20; i++) {
        container.append('<input type="radio" name="radio_group" value="' + i + '">');
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="radio_container">Choose one: </div>

    Thus you search for the container only once (unlike in the other answers) and assign a value to each radio that lets you identify the choice.

    0 讨论(0)
  • 2020-12-08 22:45
    for (var i=0;i<=20;i++)
      {
      $("#yourcontainer").append("<input type='radio' name='myRadio' />");
      }
    
    0 讨论(0)
提交回复
热议问题