0

I'm just trying to upon checking a radio button send AJAX call and radio button append using JavaScript.

I've tried several things but have not been able to get this right:

for (var i = 0; i < response.split(',').length; i++) {
    $('#radio_append').append('<input name="suggested_dates" id="suggested_dates'+count+'" value="' + response.split(',')[i] + '" class="styled chal_bhi_radio" type="radio" /><label for="suggested_dates'+count+'">' + response.split(',')[i] + '</label> <br> ')
    count++;
}

After append this radio button, there are four radio button on click on any one radio button send this AJAX call.

I'm trying several things but didn't work.

On select any checkbox it didn't show alert box. These radio button append from JavaScript.

enter image description here

$(".chal_bhi_radio").on('change', function() {
      alert("HI");
      var date_al = $(".chal_bhi_radio:checked").val();
      $.post("<?php echo $site_root;?>common/service.php?j=4", {
          date_select: date_al
        },
        function(response) {
          if (response != '') {
            per_data = $.parseJSON(response);
            if (per_data != 0) {
              $("#price_special_append").html("");
              add_basic = per_data;
              $("#price_special_append").append(" € " + add_basic + " ")
            }
          }
        });
halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

2

You should use event delegation as the newly appended elements won't have an event listener attached to them:

Note the event handler is attached to the NEAREST static element and we are using click. The value can ONLY come from this radio so no need to scan the dom for checked radios unless you have more sets of them

$('#radio_append').on("click", ".chal_bhi_radio",function(){
  alert("HI");
  var date_al = $(this).val();
});

Event delegation won't attach the event listeners directly to the .chal_bhi_radio. But instead, it will attach them to another element (here document). So when ever that element is clicked it will check if the target element match the selector (second argument ".chal_bhi_radio"). Read more about event delegation.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73