繁体   English   中英

获取javascript中输入类型复选框中所有复选框的值

[英]Get values of all checked boxes in input type checkbox in javascript

我做了一个函数来获取复选框的值并将所有值放在输入字段中。 但是我在结果中遇到问题,我想删除最后一个逗号。 我试过切片但没有成功。 请帮帮我。

<!DOCTYPE html>
<html>
<body>

<p>How would you like your coffee?</p>

<form name="myform" action="/action_page.php">
<input type="checkbox" name="coffee" value="100">With cream<br>
<input type="checkbox" name="coffee" value="150">With sugar<br>
<input type="checkbox" name="coffee" value="200">With milk<br>
<input type="checkbox" name="coffee" value="250">With tea<br>
<br>
<input type="button" onclick="myFunction()" value="Send order">
<br><br>
<input type="text" id="order" size="50">
<input type="submit" value="Submit">
</form>

<script>
function myFunction() {
  var coffee = document.forms["myform"];
  var txt = "";
  var i;
  for (i = 0; i < coffee.length; i++) {
    if (coffee[i].checked) {
      txt = txt + coffee[i].value + ", ";

    }
  }
  document.getElementById("order").value = "You ordered a coffee with: " + txt;
}
</script>

</body>
</html>

使用数组,将值推送到for循环中,然后使用join()

var txt = [];
var i;
for (i = 0; i < coffee.length; i++) {
  if (coffee[i].checked) {
    txt.push(coffee[i].value);
  }
}
document.getElementById("order").value = "You ordered a coffee with: " + txt.join(', ');

作为旁注,使用querySelectorAll()您可以只选择选中的 chekboxes,而不使用循环内的条件:

var coffee = [...document.querySelectorAll('[name="myform"] input:checked')];
var i, txt = [];

for (i = 0; i < coffee.length; i++) {
    txt.push(coffee[i].value);
}
document.getElementById("order").value = "You ordered a coffee with: " + txt.join(', ');

如果您确定txt的末尾总是有一个逗号,并且您想使用slice ,则可以运行txt = txt.slice(0,-2) -2 是因为您有", " ,这是两个字符。 但数组答案是更好的方法。

function myFunction() {
  var coffee = document.forms["myform"];
  var txt = "";
  var i;
  for (i = 0; i < coffee.length; i++) {
    if (coffee[i].checked) {
      txt = txt + coffee[i].value + ", ";

    }
  }
  document.getElementById("order").value = "You ordered a coffee with: " +txt.substring(0, txt.length - 1);

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM