首页 > 解决方案 > 在javascript中传递选中的复选框值

问题描述

这是我的 HTML 中的复选框:

<input type="checkbox" name="sides" id="1" value="French Fries" >French Fries<br />
<input type="checkbox" name="sides" id="2" value="Baked Potato">Baked Potato<br />
<input type="checkbox" name="sides" id="3"  value="Cole Slaw">Cole Slaw<br />
<input type ="button" value = "Enter my side dish selections" onclick="checkbox(sides.value1,sides.value2)"/>

我想要的是当用户单击按钮时,它应该首先选中两个复选框,然后将其显示为:

function checkbox(dish1,dish2) {
  document.getElementById("side_one").innerHTML = dish1;
  document.getElementById("side_two").innerHTML = dish1;
}

我对如何做到这一点感到困惑,你能在这里帮助我吗?

标签: javascripthtml

解决方案


您可以使用 选择前两个选中的输入[...document.querySelectorAll( ":checked" )].slice( 0, 2 );

它的作用是从 NodeList 创建一个 Array,该 NodeList 由与:checked伪类匹配的所有元素组成,并将其分割成一个包含两个项目的新 Array。

然后你只需要抓住.value找到的 <input> 元素:

document.querySelector('[type="button"]').onclick = (evt) => {
  const checked = [...document.querySelectorAll( ":checked" )].slice( 0, 2 );
  checkbox( ...checked.map( (input) => input.value ) )
};

function checkbox(dish1 = "", dish2 = "") {
  document.getElementById("side_one").innerHTML = dish1;
  document.getElementById("side_two").innerHTML = dish2;
}
<input type="checkbox" name="sides" id="1" value="French Fries" >French Fries<br />
<input type="checkbox" name="sides" id="2" value="Baked Potato">Baked Potato<br />
<input type="checkbox" name="sides" id="3"  value="Cole Slaw">Cole Slaw<br />
<input type ="button" value = "Enter my side dish selections"/>

<p id="side_one"></p>
<p id="side_two"></p>

如果你希望它只在特定元素的内容中搜索,你只需要使 CSS 选择器querySelectorAll更具体。


推荐阅读