[英]How to get values of <input type=“checkbox” /> that are checked?
[英]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.