Dvir Naim Dvir Naim - 1 month ago 8
Javascript Question

onclick doesn't work properly with bootstrap

I tried to use onclick event with Bootstrap radio-buttons to get names and attributes but some how it didn't go well.

Some of the radio-buttons triggered the event but didn't get the name or class ("undefined") and some didn't respond at all.

<div class="theContainer">
<input type="radio" class="myClass" name="options" id="option1" onclick="updateODid()" autocomplete="off" > Radio 1
<input type="radio" class="myClass" name="options" id="option2" onclick="updateODid()" autocomplete="off"> Radio 2
<input type="radio" class="myClass" name="options" id="option3" onclick="updateODid()" autocomplete="off"> Radio 3
<input type="hidden" class="findme" value="found me!">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" class="myClass" name="options" id="option1" onclick="updateODid()" autocomplete="off" > Radio 1
</label>
<label class="btn btn-primary">
<input type="radio" class="myClass" name="options" id="option2" onclick="updateODid()" autocomplete="off"> Radio 2
</label>
<label class="btn btn-primary">
<input type="radio" class="myClass" name="options" id="option3" onclick="updateODid()" autocomplete="off"> Radio 3
</label>
</div>
</div>


jsfiddle.net/2sc8mc7L/6/

Thanks!

Answer

It's not working because you have mixed javascript and jquery in a wrong way.

Please check updated snippet : https://jsfiddle.net/2sc8mc7L/12/ The onclick function should be as below :

$(".myClass").on('click',function(){
  radioButtonClick($(this));
});

$("label.btn-primary").on('click',function(){
  radioButtonClick($(this).find('.myClass'));
});

function radioButtonClick(_this){
  alert("I'm in!")
  alert (_this.attr('name'));
  alert (_this.attr('class'));
  alert (_this.closest(".theContainer").find(".findme").val());
}