greenarrow greenarrow - 3 months ago 20
jQuery Question

Jquery UI autocomplete on dynamic fields

Kindly have a look at this screen capture.

http://www.screencast.com/t/GMGBy6QF9bP

as i have shown i am trying to use jquery ui autocomplete on a dynamically generated fields, autocomplete works fine with the main field i'm using to copy & generate dynamic fields. but when adds a new field the autocomplete not working with the newly generated field.

this is my autocomplete code

$(function(){
$(".get-tasks").autocomplete({
source: baseurl+"job/job/get_tasks_autocomp",
});
})


I would like to get help from someone here to fix this, please show in Code how can i fix this.

this is the code for add new field

$(document).ready(function(){
var i=0;
$('#add_fault_fld').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" class="get-tasks job-tasks form-control" name="fault['+i+']" id="['+i+']" placeholder="" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');

});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({
//url:"name.php",
method:"POST",
data:$('#add_fault').serialize(),
success:function(data)
{
alert(data);
$('#add_fault')[0].reset();
}
});
});



}); //End

Answer

hmm, ok try this and see if it works for you. I'm using prototype to attach autocomplete function to dynamic element.

UPDATED: Added jsfiddle for demo: https://jsfiddle.net/p7pdmbgf/

UPDATED-2: https://jsfiddle.net/p7pdmbgf/3/

$('#add_fault_fld').click(function(){  
   i++;
   var element = '<tr id="row'+i+'"><td><input type="text" class="get-tasks job-tasks form-control" name="fault['+i+']" id="['+i+']" placeholder="" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>';
   $('#dynamic_field').append(element).attachAutocomplete();
});


$.fn.attachAutocomplete = function() {
   $(this).find(".get-tasks").autocomplete({
     source: baseurl+"job/job/get_tasks_autocomp",
   });
}
Comments