phcaze phcaze - 6 months ago 7
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">
</div>

<script type="text/javascript">
var selection = document.getElementById("selection");
selection.style.visibility = 'visible';
var selectionToAdd='';
var toAdd=[];
for(var indexSelectionArticles = 0 in query) {
for(var indexSelectionEntities = 0 in query[indexSelectionArticles].entities) {
if(query[indexSelectionArticles].entities[indexSelectionEntities].category){
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>';
toAdd.push(query[indexSelectionArticles].entities[indexSelectionEntities].category);
}
}
}
}
selection.innerHTML = selectionToAdd;
</script>


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(e.target.id == 'option1') {
option = 'option1';
}
else if(e.target.id == 'option2') {
option = 'option2';
}
else if(e.target.id == 'option3') {
option = 'option3';
}
else if(e.target.id == 'option4') {
option = 'option4';
}
else if(e.target.id == 'option5') {
visualizationType = 'articles';
}
else if(e.target.id == 'option6') {
visualizationType = 'entities';
}
else {
console.log(e.target.id);
}
});


Where is the error?

Thank you

Answer

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