试图存储复选框的值,但是在本地存储应用程序中似乎没有弹出chrome:(
<label id='interest'>Interests:</label>
<input type="checkbox" id="education" value="education" name="user_interest"><label class="light" for="Education">Educational purpose</label><br>
<input type="checkbox" id="CCA" value="CCA" name="user_interest">
<label class="light" for="CCA">CCA Points</label><br>
<input type="checkbox" id="development" value="development" name="user_interest"><label class="light" for="development">Development</label><br>
<input type="checkbox" id="design" value="design" name="user_interest"><label class="light" for="design">Design</label><br>
<input type="checkbox" id="business" value="business" name="user_interest"><label class="light" for="business">Business</label>
<button type="submit" onClick="signup()" id="sign_up">Sign Up</button>
<script>
function signup()
{
localStorage.setItem("users_interests" + document.getElementByClassName("light").value, document.getElementByClassName("light").value);
}
</script>
答案 0 :(得分:0)
文档getElementByClassName
中没有getElementsByClassName
这样的方法会返回节点集合,因此您需要将函数更改为以下形式:
function signup()
{
//Declare constant variable to hold the elements with class light
const lightEles = document.getElementsByClassName("light");
//Declare an array to hold the values
let eleValues = [];
//Iterate the node collection and push each element's value into the array
for(let x = 0; x < lightEles.length; x++){
eleValues.push(lightEles[x].value);
}
//Set array to localStorage key
localStorage.setItem("users_interests", eleValues);
}
答案 1 :(得分:0)
尝试
function signup()
{
var users_interests =[];
var els = document.getElementsByName("user_interest");
Array.prototype.forEach.call(els, function(el) {
if (el.type == "checkbox" && el.checked) {
users_interests.push(el.value);
}
// Do stuff here
});
localStorage.setItem("users_interests",JSON.stringify(users_interests));
console.log(JSON.parse(localStorage.getItem("users_interests")));
}