使用Jquery检查表中是否已存在“检查项”
本文关键字:检查 检查项 存在 Jquery 检查表 是否 使用 | 更新日期: 2023-09-27 18:21:06
我有一个Select2列表,并向表中添加了多个项。但我想先检查表中是否已经存在项,if不仅要添加新项,而且下面的代码不起作用。
在这个代码中,每次它都显示Not Found&添加重复行
HTML部件
<select id="select-product" multiple style="width: 300px">
</select>
代码
$("#select-product").change(function () {
debugger;
var $option = $('#select-product option');
if ($("#select-product option[value='ProductCode']").length > 0) {
alert("Found");
}
else
{
alert("Not Found");
}
$option.each(function () {
if ($(this).is(':selected')) {
debugger;
var itm = $(this).is(':selected');
var temp = $(this).attr('ProductCode');
var row = '<tr>';
row += '<td class="itmcode">' + $(this).attr('ProductCode') + '</td>';
row += '<td class="itmname">' + $(this).text().replace(temp, " ") + '</td>';
row += '<td class="unit">' + $(this).attr('Unit_UnitId') + '</td>';
row += '<td class="retprice" dir="rtl" align="right">' + $(this).attr('RetailPrice') + '</td>';
row += '<td class="col-md-1 inpqty" dir="rtl">' + '<input type="text" class="input-qty form-control col-md-3 center-block input-sm" data-id="' + $(this).val() + '" data-prod-id="' + $(this).attr('Value') + '">' + '</td>';
row += '<td class="col-md-1 disc" dir="rtl">' + '<input type="text" class="input-disc form-control input-sm">' + '</td>';
row += '<td class="tot" dir="rtl" align="right">0</td>';
row += '<td class="imgdel"><img class="btn-img-del" src="../Images/delete.png" alt="" title="Delete" /></td>';
row += '</tr>';
table.append(row);
}
});
$('#select-product').select2('data', null);
});
多种产品代码
function CallMultipleProducts() {
$.ajax({
type: "POST",
url: '/Sales/GetMultipleProducts',
contentType: "application/; charset=utf-8",
dataType: "json",
async: false,
success: function (msg) {
debugger;
if (msg._productlist.length > 0) {
debugger;
$.each(msg._productlist, function (index, item) {
debugger;
$('#select-product').append($("<option></option>")
.attr("Value", item.ProductId)
.attr("RetailPrice", item.RetailPrice)
.attr("ProductCode", item.ProductCode)
.text((item.ProductCode) + " " + (item.ProductName))
);
});
}
}
// error: AjaxError
})
}
确保在整个html中只有具有唯一id="select-product"
的select
项。
尝试以下代码,使用.find()
if ($("#select-product").find("option[value='ProductCode']").length > 0) {
alert("Found");
}
如果元素是input type="text",,请尝试将以下选项添加到您的select2选项中
$("#select-product").select2({
createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term};} }
});
如果您使用的是<select>
元素,恐怕您无法使用此选项。您必须使用input
。你可能会在这里找到有用的东西。