//这是我正在尝试的代码,但我没有获取输入类型中的值让我知道我做错了什么
<script type="text/javascript">
script for getting value from checkbox
var array = [];
$('input[type="checkbox"]').change(function() {
if ($(this).prop('checked')) {
// Add the new element if checked:
if (array.indexOf($(this).val()) < 0) {
array.push($(this).val());
}
} else {
// Remove the element if unchecked:
if (array.indexOf($(this).val()) >= 0) {
array.splice(array.indexOf($(this).val()), 1);
}
}
$('#ff_elem512').val(array.join(", "));
console.log(array);
});
</script>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" />One
<input type="checkbox" value="2" />Two
<input type="checkbox" value="3" />Three
<input type="checkbox" value="4" />Four
<input type="checkbox" value="5" />Five
<br />
//trying to get the value here from javascript to input id
<input type="text" id="ff_elem512" />
</body>
最佳答案
这是工作代码:
var array = [];
$('input[type="checkbox"]').change(function() {
if ($(this).prop('checked')) {
// Add the new element if checked:
if (array.indexOf($(this).val()) < 0) {
array.push($(this).val());
}
} else {
// Remove the element if unchecked:
if (array.indexOf($(this).val()) >= 0) {
array.splice(array.indexOf($(this).val()), 1);
}
}
$('#ff_elem512').val(array.join(", "));
console.log(array);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input type="checkbox" value="1" />One
<input type="checkbox" value="2" />Two
<input type="checkbox" value="3" />Three
<input type="checkbox" value="4" />Four
<input type="checkbox" value="5" />Five
<br />
在执行 JavaScript 代码之前,您需要添加 JQuery。
关于javascript - 无法通过复选框从输入类型中的 javascript 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44154503/