ariefbruce ariefbruce - 2 months ago 5
jQuery Question

How to make Jquery Click function with multiple radio button with different id in the last name like #radio_1, #radio_2, #radio_3

Here my HTML Code

<label><input name="radio" id="radio" type="radio" value="1"></input> <span>Radio 1</span></label>
<label><input name="radio" id="radio" type="radio" value="2"></input> <span>Radio 2</span></label>
<label><input name="radio" id="radio" type="radio" value="3"></input> <span>Radio 3</span></label>


And this is my JQuery Code

<script type="text/javascript">
jQuery.noConflict();
(function($) {
$(document).ready(function(){

$('#radio').click(function(){
var ongkir = $(this).val();
alert(ongkir);
});

});
})(jQuery);
</script>


and the result just value 1, how i get value 2 and 3 ?

Answer

The id attribute should be unique only the first element with id get selected. So always use class for the group of elements.

jQuery.noConflict();

(function($) {
    $('.radio').click(function() {
      var ongkir = $(this).val();
      alert(ongkir);
    });
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <input name="radio" class="radio" type="radio" value="1"></input> <span>Radio 1</span>
</label>
<label>
  <input name="radio" class="radio" type="radio" value="2"></input> <span>Radio 2</span>
</label>
<label>
  <input name="radio" class="radio" type="radio" value="3"></input> <span>Radio 3</span>
</label>