获取值复选框并推入数组
Get value checkbox and push in array
你能帮我看看如何让复选框的值成为一个数据数组吗?我这样编码,没有得到任何输出。谢谢你帮助我。
在我的 html 中:
<input class="form-check-input delete-checkbox" type="checkbox" name="checkbox[]" id="checkbox" value="{{ $item->id }}"data-id="{{ $item->id }}">
在我的 JS 中:
function multiple_delete(id) {
const selected = [];
$(".form-check input[type=checkbox]:checked").each(function () {
selected.push(this.value);
});
if (selected.length > 0) {
dataid = selected.join(",");
$.ajax({
url: "multiple-delete",
type: "POST",
data: +dataid,
success: function (data) {
if (data["success"]) {
alert(data["success"]);
} else {
alert(data["error"]);
console.log(data);
}
},
error: function (data) {
alert(data.responseText);
},
});
}
}
我的输出:
首先,您使用了错误的选择器。您应该将 javascript 中的 .form-check
更改为 .form-check-input
或 .delete-checkbox
。您还可以使用 jquery 的 .map()
方法轻松获取所选复选框的值。
将您的 javascript 代码更改为类似这样的内容
function multiple_delete(id) {
const selected = $(".delete-checkbox:checked").map((i, el) => el.value).get();
if (selected.length > 0) {
$.ajax({
url: "multiple-delete",
type: "POST",
data: selected.join(","),
success: function (data) {
if (data["success"]) {
alert(data["success"]);
} else {
alert(data["error"]);
console.log(data);
}
},
error: function (data) {
alert(data.responseText);
},
});
}
}
你能帮我看看如何让复选框的值成为一个数据数组吗?我这样编码,没有得到任何输出。谢谢你帮助我。
在我的 html 中:
<input class="form-check-input delete-checkbox" type="checkbox" name="checkbox[]" id="checkbox" value="{{ $item->id }}"data-id="{{ $item->id }}">
在我的 JS 中:
function multiple_delete(id) {
const selected = [];
$(".form-check input[type=checkbox]:checked").each(function () {
selected.push(this.value);
});
if (selected.length > 0) {
dataid = selected.join(",");
$.ajax({
url: "multiple-delete",
type: "POST",
data: +dataid,
success: function (data) {
if (data["success"]) {
alert(data["success"]);
} else {
alert(data["error"]);
console.log(data);
}
},
error: function (data) {
alert(data.responseText);
},
});
}
}
我的输出:
首先,您使用了错误的选择器。您应该将 javascript 中的 .form-check
更改为 .form-check-input
或 .delete-checkbox
。您还可以使用 jquery 的 .map()
方法轻松获取所选复选框的值。
将您的 javascript 代码更改为类似这样的内容
function multiple_delete(id) {
const selected = $(".delete-checkbox:checked").map((i, el) => el.value).get();
if (selected.length > 0) {
$.ajax({
url: "multiple-delete",
type: "POST",
data: selected.join(","),
success: function (data) {
if (data["success"]) {
alert(data["success"]);
} else {
alert(data["error"]);
console.log(data);
}
},
error: function (data) {
alert(data.responseText);
},
});
}
}