barryjs
barryjs

Reputation: 43

Adding radio buttons with jquery

I am trying use JQquery to add custom radio buttons to a parent element:

function createRadio(name, parentID, values) {
  var parent = $('#' + parentId);
  for (var i = 0; i < values.length; i++) {
      $('<input />', {
        type: 'radio',
        name: name,
        value: values[i]
    }).appendTo(parent);
    $('<label />', {
        'for': 'cb',
        text: values[i]
    }).appendTo(parent);
  }
}

However, this code works:

    $(document).ready(function () {
        $('<input type="radio" name="rad" value="a">').appendTo('#radios');
        $('<input type="radio" name="rad" value="b">').appendTo('#radios');
        $('<input type="radio" name="rad" value="b">').appendTo('#radios');
    });

But this doesn't:

    $(document).ready(function () {
        createRadio('rad', 'radios', ['a', 'b', 'c']);
    });

The HTML has a div who id is radios:

 <div id="radios">Radios</div>

Thanks for your time.

Upvotes: 1

Views: 41

Answers (1)

Bhavesh G
Bhavesh G

Reputation: 3028

Your code is correct but you've mistaken in spellings parentID and parentId.

Check spelling of parentID in both function declaration (function createRadio(name, parentID, values)) parameters and var parent = $('#' + parentId);

It should be,

function createRadio(name, parentID, values) {
var parent = $('#' + parentID);
.....
.....
.....

Upvotes: 2

Related Questions