phcaze phcaze - 1 year ago 103
HTML Question

Programmatically add radio items in javascript and onclick event

I have a radio button and I'm adding elements to it programmatically. As you can see I set the onclick event in the html code but it is not triggered when I push the item.

<div class="btn-group" data-toggle="buttons" name="radio" id="selection">

<script type="text/javascript">
var selection = document.getElementById("selection"); = 'visible';
var selectionToAdd='';
var toAdd=[];
for(var indexSelectionArticles = 0 in query) {
for(var indexSelectionEntities = 0 in query[indexSelectionArticles].entities) {
if($.inArray(query[indexSelectionArticles].entities[indexSelectionEntities].category, toAdd) == -1) {
selectionToAdd=selectionToAdd + '<label class="btn btn-default"><input type="radio" onclick="javascript:console.log(whatever);" name="options" id="option'+query[indexSelectionArticles].entities[indexSelectionEntities].category+'">&nbsp; <i class="fa fa-'+query[indexSelectionArticles].entities[indexSelectionEntities].category+'"></i>&nbsp; '+capitalizeFirstLetter(query[indexSelectionArticles].entities[indexSelectionEntities].category)+' &nbsp;</input></label>';
selection.innerHTML = selectionToAdd;

The item are correctly added but the onclick is not triggered. I also tried with a function but the result is the same. I also tried the listener as follows, which works with other radios in the page but not for this one:

$('input[type="radio"]').on('click change', function(e) {

if( == 'option1') {
option = 'option1';
else if( == 'option2') {
option = 'option2';
else if( == 'option3') {
option = 'option3';
else if( == 'option4') {
option = 'option4';
else if( == 'option5') {
visualizationType = 'articles';
else if( == 'option6') {
visualizationType = 'entities';
else {

Where is the error?

Thank you

Answer Source

You're wrapping the <input> in a <label>. Wouldn't the onclick event need to be on the <label> rather than the <input>?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download