How to make autocomplete for form dynamic

前端 未结 1 715
失恋的感觉
失恋的感觉 2021-01-25 05:04

i have trouble using autocomplete with dynamic created input. I can\'t get autocomplete to bind to the new inputs.

This code autocomplete I used on the first input

1条回答
  •  旧巷少年郎
    2021-01-25 05:46

    Your issue is because the #nama-N element doesn't exist in the DOM when you try to initialise the autocomplete function on it.

    To fix this, move your first block of code inside the click handler, after append() has been called. Try this:

    $('#tambah').click(function(e) {
      e.preventDefault();
    
      var i = $('input').size() + 1;
      var input = '';
      input += '';
      input += '';
      input += '';
      input += '';
      input += '';
      input += ''
      input += '';
    
      $('#box').append(input);
    
      // attach autocomplete here as the element now exists in the DOM
      $('#nama-' + i).autocomplete({
        source: "get_barang.php",
        minLength: 2,
        select: function(event, ui) {
          $('#kode-0').val(ui.item.kode);
          $('#harga-0').val(ui.item.harga);
        }
      });
    });
    

    0 讨论(0)
提交回复
热议问题