diff options
Diffstat (limited to 'static/script.js')
-rw-r--r-- | static/script.js | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/static/script.js b/static/script.js new file mode 100644 index 0000000..ced777c --- /dev/null +++ b/static/script.js @@ -0,0 +1,68 @@ +"use strict"; + +var html = `` +for (var table in data) { + var s = `` + for (var idx in data[table]) { + let tag = table + '|' + idx + s += `<input type="checkbox" id="ingredient${tag}" x-ingredient="${tag}"> + <label for="ingredient${tag}">${data[table][idx].name}</label>` + } + html += `<fieldset><legend>${table}</legend>${s}</fieldset>` +} +html += `<fieldset><legend>Dressing amount</legend> + <input type="radio" name="dressing-amount" id="light" value="light"> + <label for="light">Light</label><br> + <input type="radio" name="dressing-amount" id="medium" value="medium"> + <label for="medium">Medium</label><br> + <input type="radio" name="dressing-amount" id="heavy" value="heavy"> + <label for="heavy">Heavy</label><br> + </fieldset>` + +nutrition = document.getElementById('nutrition') +form = document.getElementById('form') +form.innerHTML = html + +let multipliers = {'none': 0, 'light': 1, 'medium': 2, 'heavy': 3} + +function calculateNutrition() { + let total = {} + let dressingAmount = form.elements['dressing-amount'].value || 'none' + for (var el of document.querySelectorAll('input:checked')) { + if (el.getAttribute('type') == 'radio') { + continue + } + let tag = el.getAttribute('x-ingredient') + let table = tag.split('|')[0] + let idx = tag.split('|')[1] + let row = data[table][idx] + for (var [name, val] of Object.entries(row)) { + if (typeof val == 'string') { + continue + } + if (!total[name]) { + total[name] = 0 + } + let multiplier = 1 + if (table == 'Dressings') { + multiplier = multipliers[dressingAmount] + } + if (multiplier > 0) { + total[name] += multiplier*val + } + } + } + return total +} + +form.addEventListener('change', function() { + let total = calculateNutrition() + var s = ` + Calories: ${total.calories}<br> + Carbohydrates (g): ${total.total_carbs}<br> + Dietary fiber (g): ${total.dietary_fiber}<br> + Fat (g): ${total.total_fat}<br> + Protein (g): ${total.protein}<br> + ` + nutrition.innerHTML = s +}) |