我想获取数组中的所有输入值并使用alert显示。请检查下面的代码。我正在通过类名“check_item”尝试警报,但在警报弹出窗口中收到未定义的错误。我的目标是显示在点击“上传”按钮
之前检查过的值<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form>
<input type="checkbox" name="check_item" id="check_item" class="check_item" value="1">Item 1<br/>
<input type="checkbox" name="check_item" id="check_item" class="check_item" value="2">Item 2<br/>
<input type="checkbox" name="check_item" id="check_item" class="check_item" value="3">Item 3<br/>
<input type="button" class="uploadExternal" value="Upload"/>
</form>
<script type="text/javascript">
$(document).on("click", ".uploadExternal", function (e) {
var x = document.getElementsByClassName("check_item").value;
alert(x);
});
</script>
</body>
</html>
答案 0 :(得分:0)
使用 jQuery :
$(document).on("click", ".uploadExternal", function(e) {
var x = [];
$(".check_item").each(function(index, item){
x.push({
index: index,
value: item.value,
checked: item.checked
});
});
alert(JSON.stringify(x));
console.log(x);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form>
<input type="checkbox" name="check_item" class="check_item" value="1">Item 1<br/>
<input type="checkbox" name="check_item" class="check_item" value="2">Item 2<br/>
<input type="checkbox" name="check_item" class="check_item" value="3">Item 3<br/>
<input type="button" class="uploadExternal" value="Upload" />
</form>
</body>
</html>
&#13;
如果只需要检查值,则使用简单条件进行过滤:
$(document).on("click", ".uploadExternal", function(e) {
var x = [];
$(".check_item").each(function(index, item) {
if (item.checked) {
x.push(item.value);
}
});
alert(!x.length ? 'Nothing selected ' : JSON.stringify(x));
console.log(x);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form>
<label><input type="checkbox" name="check_item" class="check_item" value="1">Item 1</label>
<label><input type="checkbox" name="check_item" class="check_item" value="2">Item 2</label>
<label><input type="checkbox" name="check_item" class="check_item" value="3">Item 3</label>
<input type="button" class="uploadExternal" value="Upload"/>
</form>
</body>
</html>
&#13;