I need to add products for sale with dynamic input field. The field use autocomplete from Jquery ui and later I want to fetch both ui.label and ui.value.
My dynamic Input Field Code
$(document).ready(function () {
var count = 1;
dynamic_field(count);
function dynamic_field(number) {
html = '<tr><div class="input_fields_wrap">';
html += '<td><input type="text" name="productname[]" class="form-control producttarget" id="product"/></td></div>';
html += '<td><input type="text" name="amount[]" class="form-control" /></td>';
if (number > 1) {
html += '<td><button type="button" name="remove" id="" class="btn btn-danger remove">Remove</button></td></tr>';
$('tbody').append(html);
} else {
html += '<td><button type="button" name="add" id="add" class="btn btn-success">Add</button></td></tr>';
$('tbody').html(html);
}
}
$(document).on('click', '#add', function () {
count++;
dynamic_field(count);
});
$(document).on('click', '.remove', function () {
count--;
$(this).closest("tr").remove();
});
});
I want to fetch productname, productid (which using autocomplete) and amount. and store it to database after form submit.
My Autocomplete Code
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$('body').on('click', '.producttarget', function(e) {
$(this).autocomplete({
source: function( request, response ) {
// Fetch data
$.ajax({
url:"{{route('autocomplete')}}",
type: 'post',
dataType: "json",
data: {
_token: CSRF_TOKEN,
search: request.term
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
$(this).val(ui.item.label); // this one worked
//this my problems.val(ui.item.value);
return false;
}
});
});
But the problem is, I don't know how to store ui.value in dynamic input field when i use .onclick and target class for triggering autocomplete function.
My Controller Code
public function search(Request $request)
{
$search = $request ->search;
$result = Product::where('productname', 'LIKE', '%'. $search. '%')->get();
$response = array();
foreach($result as $r){
$response[] = array("value"=>$r->id,"label"=>$r->productname);
}
echo json_encode($response);
exit;
}
Once i achieve that i probably gonna ask how to fetch the inputted array data into database. I feel stupid but this problem got me stuck for whole day, googling.