以下代码包含带有不同类型食物选项的复选框。
如果任务是将复选框存储到会话存储中,并在以后检索它们,那么如何使用JavaScript存储和检索复选框,而不使用JQuery,JSON或任何外部库?
"use strict";
function validate() {
var result = true;
var food = getFood();
if (result) {
saveFood(food)
}
return result;
}
function getFood() {
var foodType = "unknown";
var foodArray = document.getElementById("food").getElementsByTagName("input");
for (var i = 0; i < foodArray.length; i++) {
if (foodArray[i].checked) {
foodType = foodArray[i].value;
}
}
return foodType;
}
function storeFood(food) {
sessionStorage.food = food;
}
function retrieveFood() {
switch (sessionStorage.food) {
case "Pizza":
document.getElementById("pizza").checked = true;
break;
case "Hamburger":
document.getElementById("hamburger").checked = true;
break;
case "Sandwich":
document.getElementById("sandwich").checked = true;
break;
}
}
function init() {
if (document.getElementById("food-page") != null) {
retrieveFood();
document.getElementById("food-form").onsubmit = validate;
}
}
window.onload = init;
<body id"food-page">
<form id="food-form" method="post" action="server">
<fieldset id="food">
<legend>Foods</legend>
<p>
<label for="pizza">Pizza</label>
<input type="checkbox" id="pizza" class="food-choices" name="food-checkboxes" checked="checked" value="Pizza" required="required" />
<label for="hamburger">Hamburger</label>
<input type="checkbox" id="hamburger" class="food-choices" name="food-checkboxes" value="Hamburger" />
<label for="sandwich">Sandwich</label>
<input type="checkbox" id="sandwich" class="food-choices" name="food-checkboxes" value="Sandwich" />
</p>
</fieldset>
</form>
</body>
犯罪嫌疑人X
FFIVE
慕运维8079593
相关分类