gpt4 book ai didi

javascript - 带有复选框的表 - 选择所有复选框并将值传递给 AJAX 脚本

转载 作者:行者123 更新时间:2023-12-03 03:49:24 26 4
gpt4 key购买 nike

我有一个表,第一列中有一个复选框 - 当选中时,它会执行一个 AJAX 脚本,用所选值更新 PHP session 变量。这一切都运行良好,但我现在需要扩展它以在第一列顶部有一个复选框,以允许用户选择表中的所有项目并将所选项目的值(例如逗号分隔)作为AJAX 脚本的参数 - 假设我为此需要一个新脚本。

这是我到目前为止所拥有的:

$(document).ready(function() {
$("input.select-item").click(function() {
var productID = $(this).val();
// Create a reference to $(this) here:
$this = $(this);
$.post('productSelections.php', {
type: 'updateSelections',
productID: productID,
selectionType: 'single'
}, function(data) {
data = JSON.parse(data);
if (data.error) {
var ajaxError = (data.text);
var errorAlert = 'There was an error updating the Product Selections';
$this.closest('td').addClass("has-error");
$("#updateSelectionsErrorMessage").html(errorAlert);
$("#updateSelectionsError").show();
return; // stop executing this function any further
} else {
$this.closest('td').addClass("success")
$this.closest('td').removeClass("danger");
}
}).fail(function(xhr) {
var httpStatus = (xhr.status);
var ajaxError = 'There was an error updating the Product Selections';
$this.closest('td').addClass("danger");
$("#updateSelectionsErrorMessage").html(ajaxError);
$("#updateSelectionsError").show();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-condensed table-striped table-bordered">
<thead>
<th><input type="checkbox" class="select-all checkbox" name="select-all" /></th>
<th class="text-center" scope="col">Product ID</th>
<th class="text-center" scope="col">Description</th>
</thead>
<tbody>

<tr class="" id="85799">
<td id="AT36288"><input type="checkbox" class="select-item checkbox" name="select-item" value="AT36288" /></td>
<td>AT36288</td>
<td>Apples</td>
<td></td>
</tr>
<tr class="" id="85800">
<td id="AT36289"><input type="checkbox" class="select-item checkbox" name="select-item" value="AT36289" /></td>
<td>AT36289</td>
<td>Bananas</td>
<td></td>
</tr>
<tr class="" id="85801">
<td id="AT36290"><input type="checkbox" class="select-item checkbox" name="select-item" value="AT36290" /></td>
<td>AT36290</td>
<td>Oranges</td>
<td></td>
</tr>
<tr class="" id="85803">
<td id="AT36292"><input type="checkbox" class="select-item checkbox" name="select-item" value="AT36292" /></td>
<td>AT36292</td>
<td>Grapes</td>
<td></td>
</tr>
</tbody>
</table>

我在第一行添加了一个复选框,可用于选择所有项目 - 本质上相当于逐个单击每个复选框。不确定如何扩展或创建一个新脚本,单击该脚本时会检查每个复选框并将 ID 值传递给可以包含在 AJAX 脚本中的变量?

最佳答案

$('.select-all').on('click', function(){
var values = []; // will contain all checkbox values that you can send via ajax
$('table > tbody input[type="checkbox"]').each(function(i, el) {
$(el).prop('checked', true);
values.push(el.value);
});
});

关于javascript - 带有复选框的表 - 选择所有复选框并将值传递给 AJAX 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45231507/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com