I have an edit page in laravel where there is multiple data product that using foreach to display, and i want to autocomplete the name of product using ajax but it doesn't work. but i dont get any error messages.
here is the code
@foreach($product as $item){
<input type="text" name="product" id="product" value="{{ $item->name }}"/>
<input type="number" name="qty" id="qty" value="{{ $item->quantity }}"/>
<input type="number" name="price" id="price" value="{{ $item->price }}"/>
}
and the script
$(document).ready(function(){
$('#product').autocomplete({
source: function(request, response){
console.log(request.term)
$.ajax({
url:"{{ route('autocompleteproduct')}}",
dataType: "json",
data: {
search: request.term
},
success: function(data){
response(data);
},error:function(){
alert('error');
}
});
},
select: function(event, ui){
$('#product').val(ui.item.label);
return false;
}
});
});
CodePudding user response:
As I mentioned in my Comment, ID's on divs should be unique, Here you are looping over items spamming the the id of "#product" on each one. use a class, or be more specific with each products actual id
below I have removed the IDs off each input as you are not using any labels they are not required. I have also wrapped them in a class to loop over each one so we can target the children specifically
@foreach($product as $item)
<div class="product-inputs" id="product-{{ $item->id }}">
<input type="text" name="product" value="{{ $item->name }}">
<input type="number" name="qty" value="{{ $item->quantity }}">
<input type="number" name="price" value="{{ $item->price }}">
</div>
@endfor
$(document).ready(function(){
$('.product-inputs').each(function() {
var id = $(this).attr('id');
var input = $('#' id ' input[name=product]');
input.autocomplete({
source: function(request, response){
console.log(request.term)
$.ajax({
url:"{{ route('autocompleteproduct')}}",
dataType: "json",
data: {
search: request.term
},
success: function(data){
response(data);
},error:function(){
alert('error');
}
});
},
select: function(event, ui){
input.val(ui.item.label);
return false;
}
});
});
});