Reputation: 1273
I would like to make a form with list of products.
When the user starts typing the product name, autocomplete should show the available options by name (first array element).
When the user chooses a product, the second form control should display a price (second array element).
Here is my code:
HTML:
Product name:
<textarea class="form-control" id="product_name" name="product_name" rows="1" cols="70" placeholder="" type="text" required></textarea>
<br>
Product price:
<textarea class="form-control" id="product_price" name="product_price" rows="1" cols="70" placeholder="" type="text" required>
</textarea>
JS:
$(function() {
var tagi = [
["product_name_1", "10"],
["produc_name_2", "20"],
["produc_name_3", "20"],
];
$( "#product_name, #product_price" ).autocomplete({
source: tagi[0,1]
});
});
...and js fiddle: http://jsfiddle.net/dNLQa/159/
I am trying get this to work but I am stuck.
PS. The array will be generated by PHP, so if this needs to be in a different format I can do that easily.
Upvotes: 1
Views: 1748
Reputation: 3233
You can separately call autocomplete
and when select product
, you can forcefully change price
field.
FIDDLE
$( function() {
function setPriceByProduct(prod, values) {
for (var i = 0, len = values.length; i < len; i++) {
console.log(values[i][0])
if (values[i][0] == prod) {
$('#product_price').val(values[i][1]);
break;
}
}
}
var tagi = {
"product_name_1": "10",
"product_name_2":"20",
"product_name_3" : "20"
};
tagi1 = Object.keys(tagi);
var tagi2 = Object.values(tagi);
$( "#product_name" ).autocomplete({
source: tagi1,
select: function(event, ui){
$('#product_price').val(tagi[ui.item.value]);
}
});
$( "#product_price" ).autocomplete({
source: tagi2
});
});
Upvotes: 2
Reputation: 386
I hope I understood your problem correctly. If so, you could search for the product if the user selected one from the autocomplete.
Forked fiddle: http://jsfiddle.net/vnxa2b09/4/
$(function () {
function setPriceByProduct(prod, values) {
for (var i = 0, len = values.length; i < len; i++) {
if (values[i][0] == prod) {
$('#product_price').val(values[i][1]);
break;
}
}
}
var tagi = [
["product_name_1", "10"],
["produc_name_2", "20"],
["produc_name_3", "20"],
];
$("#product_name, #product_price").autocomplete({
source: tagi.map(function(val){return val[0]}),
select: function (event, ui) {
setPriceByProduct(ui.item.value, tagi);
}
});
});
Upvotes: 2