javascript - 在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;
}
我对如何做到这一点感到困惑,你能在这里帮助我吗?
解决方案
您可以使用 选择前两个选中的输入[...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
更具体。
推荐阅读
- visual-studio - Visual Studio Live Share:作为主持人如何向我的参与者授予访问/权限
- python - 使用 python/selenium 保存完整的网页(包括 css、图像)
- angular - ngDestroy 上的 Angular 删除 locationStrategyListener
- powershell - 如何在不添加空列的情况下偏移 system.Data.DataTable?
- mysql - 当 else 等于 NULL 时执行 if - else 语句的语法错误
- javascript - 递归操作然后跳出循环
- jmeter - jmeter中不同线程组的吞吐量分布
- c# - 检查类的实例是否存在具有某些属性
- java - Java将字母保存到数组
- unity3d - 如何将 ar 内容从一台设备共享到另一台设备?