Reputation: 579
I am trying to get data from mysql and use it to calculate energy, proteins, carbs and fat.
Formula:
The formula for energy: (energy*inp_size_a_1)/100;
The formula for proteins: (proteins*inp_size_a_1)/100;
The formula for carbs: (carbs*inp_size_a_1)/100;
The formula for fat: (fat*inp_size_a_1)/100;
From search.php I get json data:
[{
"food_name": "Frosne ekstra grove rundstykker",
"energy": "250",
"proteins": "18",
"carbohydrates": "25",
"fat": "6"
}, {
"food_name": "Frosen brokkoliblanding",
"energy": "26",
"proteins": "2",
"carbohydrates": "4",
"fat": "0"
}, {
"food_name": "Frossen kyllingfilet",
"energy": "94",
"proteins": "21",
"carbohydrates": "1",
"fat": "0"
}]
This is my HTML:
<!-- Food Autocomplete -->
<script>
$(function() {
$( "#inp_meal_a_1" ).autocomplete({
source: 'search.php'
});
});
</script>
<!-- //Food Autocomplete -->
<input type="text" name="inp_size_a_1" value="" size="3" tabindex="6" id="inp_size_a_1" />
<input type="text" name="inp_meal_a_1" value="" size="40" tabindex="8" id="inp_meal_a_1" />
<input type="text" name="inp_energy_a_1" value="" size="10" id="inp_energy_a_1" />
<input type="text" name="inp_proteins_a_1" value="" size="10" id="inp_proteins_a_1" />
<input type="text" name="inp_carbs_a_1" value="" size="10" id="inp_carbs_a_1" />
<input type="text" name="inp_fat_a_1" value="" size="10" id="inp_fat_a_1" />
What should I do to complete this?
Upvotes: 0
Views: 306
Reputation: 1332
First change your json to look like this:
[{
"value": "Frosne ekstra grove rundstykker",
"energy": "250",
"proteins": "18",
"carbohydrates": "25",
"fat": "6"
}, {
"value": "Frosen brokkoliblanding",
"energy": "26",
"proteins": "2",
"carbohydrates": "4",
"fat": "0"
}, {
"value": "Frossen kyllingfilet",
"energy": "94",
"proteins": "21",
"carbohydrates": "1",
"fat": "0"
}]
Whatever value you need in autocomplete should be in "value" in your json. Your code should be:
<script>
$(function() {
$( "#inp_meal_a_1" ).autocomplete({
source: 'search.php'
});
$('#inp_meal_a_1').on('autocompleteselect', function (e, ui) {
var val = $('#inp_size_a_1').val();
var energy = ui.item.energy;
var proteins = ui.item.proteins;
var carbohydrates = ui.item.carbohydrates;
var fat = ui.item.fat;
$("#inp_energy_a_1").val((energy*val)/100);
$("#inp_proteins_a_1").val((proteins*val)/100);
$("#inp_carbs_a_1").val((carbohydrates*val)/100);
$("#inp_fat_a_1").val((fat*val)/100);
});
});
</script>
Upvotes: 1
Reputation: 167212
Give the change
event with it. Almost you are there:
$( "#inp_meal_a_1" ).autocomplete({
source: 'search.php'
}).change(function () {
// Set your values here.
$("#inp_meal_a_1").val();
$("#inp_energy_a_1").val();
$("#inp_proteins_a_1").val();
$("#inp_carbs_a_1").val();
$("#inp_fat_a_1").val();
});
Upvotes: 0