javascript - 使用 JavaScript 从表单获取复选框值并添加到 JSON 字符串

标签 javascript

尝试提取表单值并通过 JSON 字符串将其放入 localStorage 中。此代码适用于除复选框值之外的所有内容。我如何获取复选框值?请并谢谢!

<form id="myForm">
<input type="submit" name="submit" value="submitOrder"> 
</form>

const userOrder = {};

function getValues(e) {
  // turn form elements object into an array
  var elements = Array.prototype.slice.call(e.target.elements);

  // go over the array storing input name & value pairs
  elements.forEach((el) => {
    if(el.type !== "submit" && el.type !=="button") {
      userOrder[el.name] = el.value;
    }
  });

  // finally save to localStorage
  localStorage.setItem('userOrder', JSON.stringify(userOrder));
}  

document.getElementById("myForm").addEventListener("submit", getValues);

console.log(localStorage.getItem('userOrder'));

最佳答案

使用复选框的 .checked 属性来判断它是否被选中

const userOrder = {};
function getValues(e) {
  e.preventDefault();
  // turn form elements object into an array
  //you can also use Array.from(e.target.elements)
  var elements = Array.prototype.slice.call(e.target.elements);
  console.log(elements);
  // go over the array storing input name & value pairs
  elements.forEach((el) => {
    if(el.type == "checkbox") {
      userOrder[el.name] = el.checked;
    }
  });
  console.log(userOrder);
  // finally save to localStorage
  //localStorage.setItem('userOrder', JSON.stringify(userOrder));
}  

document.getElementById("myForm").addEventListener("submit", getValues);

//console.log(localStorage.getItem('userOrder'));
<form id="myForm">
<input type="checkbox" name="checkbox-0"> 
<input type="checkbox" name="checkbox-1"> 
<input type="checkbox" name="checkbox-2"> 
<input type="submit" name="submit" value="submitOrder"> 
</form>

关于javascript - 使用 JavaScript 从表单获取复选框值并添加到 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49203171/

相关文章:

javascript - Bot Framework [Node.js] Bot 不匹配单词

javascript - 加载动态内容时jquery未终止的字符串文字

javascript - 使用 Javascript 获取 Google Analytics ID

javascript - 如何获取表单内输入的值?

javascript - 对动态添加的组合框进行 Bootstrap 验证器验证

javascript - 循环内异步函数的调用层次结构?

javascript - React useMemo 钩子(Hook)用例

javascript - D3 渐变起点

javascript - JQtouch Onclick 在移动设备上的问题

javascript - 服务器端或客户端长轮询?