0

I have dynamic fields which can be added by users. The fields contain of a selection field and input field. I want to put on change event on the selection field but failed. I tried using class name but nothing happen.

This is the dynamic added field code:

  <div class="form-group">
     <div class="row">
        <input type="button" class="add-row" value="Add Row">
          <button type="button" class="delete-row">Delete Row</button>
     </div>
  </div>



 <script>
 count=1;
 $(document).ready(function(){
    $(".add-row").click(function(){
        var markup = '<tr><td><input type="checkbox" name="rekod" style="width:20px"></td>';
        markup +=  '<td><select class="nama" name="nama[]" style="width:320px"><option value="">Pilih</option>
        <?php foreach($nama as $key => $value):echo '<option value="'.$key.'">'.addslashes($value).'</option>'; endforeach; ?></select></td>';
        markup +=  '<td><input type="text" class="no"  name="no[]" style="width:150px"></td>';
        markup +=  '<td class="col-lg-1"><input type="text" class="form-control bahagian" name="bahagian[]" style="width:100px"></td>';
        markup +=  '<td class="col-lg-1"><input type="text" name="telefon[]" style="width:100px"></td>';
        markup +=  '<td class="col-lg-1"><input type="text" name="ext[]" style="width:100px"></td></tr>';
        $("table tbody").append(markup);
        count++;
    });

    $("select.nama").change(function() {
            alert('done it');
        });


    // Find and remove selected table rows
    $(".delete-row").click(function(){
        $("table tbody").find('input[name="rekod"]').each(function(){
            if($(this).is(":checked")){
                $(this).parents("tr").remove();
            }
        });
    });
});    
</script>

I am using jquery 1.12.4. Can anyone help me to trigger the on change event? Without dynamic field, I am able to trigger the event.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
joun
  • 656
  • 1
  • 8
  • 25
  • 1
    Use delegated events to bind the click event to dynamically created elements `$(document).on('click', 'select.nama', function() { alert('done it'); });` – 4b0 Feb 18 '20 at 05:51
  • I made you a snippet. It does not run. See the console errors – mplungjan Feb 18 '20 at 05:52
  • Thanks @Shree...your answer helped me..just I change to change event. if you post it as an answer I will accept it..Thanks for your help – joun Feb 18 '20 at 05:57
  • Sorry mr, if this platform for brilliant developers only. I do try search for related title for days and I am stucked. That's why I asked here. – joun Feb 18 '20 at 06:11

0 Answers0