jQuery Ajax带复选框的Autocomplete无法保留历史选中值如何解决
问题原因
每次触发新搜索时,你直接用$("#resultDiv").html("")清空了结果区域的所有DOM,之前勾选的复选框被一并删除,提交时自然只能拿到当前页面展示的选中值。
实现方案
你需要用全局数组存储所有历史选中项,不依赖临时渲染的DOM存储选中状态,修改后的代码如下:
HTML代码
<input type="text" id="autouser" name="coin" class="form-control"> <!-- 新增隐藏域用来存储所有选中值,提交到后端 --> <input type="hidden" id="selectedCoins" name="selectedCoins"> <div id="resultDiv"></div>
JS代码
$(document).ready(function(){ // 全局数组存储所有选中的币种 let selectedCoinList = []; // 监听结果区域复选框的勾选动作 $('#resultDiv').on('change', 'input[type="checkbox"]', function() { const coinVal = $(this).val(); if($(this).is(':checked')) { // 勾选时加入数组,避免重复 if(!selectedCoinList.includes(coinVal)) { selectedCoinList.push(coinVal); } } else { // 取消勾选时从数组移除 selectedCoinList = selectedCoinList.filter(item => item !== coinVal); } // 同步更新到隐藏域 $('#selectedCoins').val(selectedCoinList.join(',')); }); $( "#autouser" ).autocomplete({ source: function( request, response ) { // Fetch data $.ajax({ url:'<?php echo base_url();?>main/CoinReords', type: 'post', dataType: "json", data: { search: request.term }, success: function( data ) { $("#resultDiv").html(""); $.each(data, function(i, record) { // 检查当前项是否已经被选中,是的话默认加checked属性 const isChecked = selectedCoinList.includes(record.label) ? 'checked' : ''; $("#resultDiv").append(`<input type='checkbox' value='${record.label}' id='chk-${i}' ${isChecked} /> ${record.label}`); }); } }); }, select: function (event, ui) { $('#autouser').val(ui.item.label); return false; } }); });
后端接收说明
PHP后端直接获取$_POST['selectedCoins'],用explode(',', $_POST['selectedCoins'])拆分就能得到所有历史和当前勾选的复选框值。
内容的提问来源于stack exchange,提问作者amit
相关产品推荐
相关产品推荐

