我的程序需要将多个复选框的值存储在会话存储中(选中或未选中),以便当用户返回此页面时,它们已被选中或未选中。我找到的这个问题的所有解决方案都涉及到我们不应该使用的JQuery的使用。
这是复选框的HTML
<fieldset>
<legend>Skills List</legend>
<p> <label for="teamwork">Teamwork</label>
<input type="checkbox" id="teamwork" name="Skill[]" value="Teamwork" checked="checked"/>
<label for="rubyskills">Ruby Experience</label>
<input type="checkbox" id="rubyskills" name="Skill[]" value="Rubyskills"/>
<label for="efficiency">Efficiency</label>
<input type="checkbox" id="efficiency" name="Skill[]" value="Efficiency"/>
<label for="communication">Communication</label>
<input type="checkbox" id="communication" name="Skill[]" value="Communication"/>
<label for="other">Other</label>
<input type="checkbox" id="other" name="Skill[]" value="other"/>
</p>发布于 2019-04-30 08:49:01
因此,在vanilla JS中,这就是如何在给定的字段集中获取所有检查过的输入。如果你可以用更多的细节和代码更新你的问题,关于如何保存到session storage,我可以提供进一步的帮助。
let fieldset = document.getElementById("fieldset1") // get fieldset element
let p = fieldset.children[1]; // the p tag
let pchildren = p.children; // the contents of the p tag
let inputs = []; // where we will hold the input elements that are checked
for (let x = 0; x < pchildren.length; x++) { // looping through to get only the inputs that are checked
if (pchildren[x].nodeName == "INPUT" && pchildren[x].checked) {
inputs.push(pchildren[x]) // pushing into array
}
}
console.log(inputs);发布于 2019-04-30 08:56:53
谢谢,不过我已经解决了
function store_data() {
var teamwork = document.getElementById("teamwork").checked;
var rubyskills = document.getElementById("rubyskills").checked;
var efficiency = document.getElementById("efficiency").checked;
var communication = document.getElementById("communication").checked;
sessionStorage.setItem("teamwork", teamwork);
sessionStorage.setItem("ruby", rubyskills);
sessionStorage.setItem("efficiency", efficiency);
sessionStorage.setItem("communication", communication);
sessionStorage.setItem("other", other);
}
function prefill_form() {
if(sessionStorage.teamwork == "true") {
document.getElementById("teamwork").checked = true;
}
if(sessionStorage.ruby == "true") {
document.getElementById("rubyskills").checked = true;
}
if(sessionStorage.efficiency == "true") {
document.getElementById("efficiency").checked = true;
}
if(sessionStorage.communication == "true") {
document.getElementById("communication").checked = true;
}
if(sessionStorage.other == "true") {
document.getElementById("other").checked = true;
}
} https://stackoverflow.com/questions/55912415
复制相似问题