【发布时间】:2019-07-03 19:08:36
【问题描述】:
我有:
- 多个复选框
- 提交按钮
- 一个 JSON 字符串对象。
- 一个检查哪些复选框被选中的函数,并在我的提交按钮上使用一个事件监听器在警报或 console.log 中返回它们的值。
- 输出 DIV
如何比较从检查哪些复选框被选中的函数获得的值与 JSON 字符串对象中的值,并将它们回显到输出 DIV 中?假设我选中了“Cheese”和“Garlic”框,并期望收到以下输出:
- 食谱 1:奶酪、番茄、大蒜
- 食谱 2:奶酪、土豆、蛋黄酱、牛肉、大蒜、黄油
HTML:
<form action="" method="">
<input type="checkbox" value="Cheese">Cheese<br>
<input type="checkbox" value="Tomato">Tomato<br>
<input type="checkbox" value="Garlic">Garlic<br>
<input type="checkbox" value="Bacon">Bacon<br>
<input type="checkbox" value="Paprika">Paprika<br>
<input type="checkbox" value="Onion">Onion<br>
<input type="checkbox" value="Potato">Potato<br>
<input type="checkbox" value="Mayo">Mayo<br>
<input type="checkbox" value="Beef">Beef<br>
<input type="checkbox" value="Garlic">Garlic<br>
<input type="checkbox" value="Butter">Butter<br>
<input type="button" value="Get recipes" id="getRecipesButton">
</form>
<div id="output">The results end up here</div>
JS:
//Recipes JSON-string:
var recipes = [
{
name:"recipe1",
ingredients:
[
{ingredient:"Cheese"},
{ingredient:"Tomato"},
{ingredient:"Garlic"}
]
},
{
name:"recipe2",
ingredients:
[
{ingredient:"Cheese"},
{ingredient:"Bacon"},
{ingredient:"Paprika"},
{ingredient:"Onion"}
]
},
{
name:"recipe3",
ingredients:
[
{ingredient:"Cheese"},
{ingredient:"Potato"},
{ingredient:"Mayo"},
{ingredient:"Beef"},
{ingredient:"Garlic"},
{ingredient:"Butter"}
]
}
];
//Test to retrieve single, specific entries:
// console.log(recipes[1].ingredients[0].ingredient);
//Test to get/return the checked values of the checkboxes:
function selectedBoxes(form) {
let selectedBoxesArr = [];
let inputFields = form.getElementsByTagName('input');
let inputFieldsNumber = inputFields.length;
for(let i=0; i<inputFieldsNumber; i++) {
if(
inputFields[i].type == 'checkbox' &&
inputFields[i].checked == true
) selectedBoxesArr.push(inputFields[i].value);
}
return selectedBoxesArr;
}
var getRecipesButton = document.getElementById('getRecipesButton');
getRecipesButton.addEventListener("click", function(){
let selectedCheckBoxes = selectedBoxes(this.form);
alert(selectedCheckBoxes);
});
【问题讨论】:
标签: javascript json checkbox lookup