我正在使用jquery动态添加和删除表的行。类似于this。
我的问题是,如何检查表格中是否已存在条目(output type
和output number
)?这样我就不会添加2个或更多相似的条目,而是更新现有的条目,或者只是忽略或发出警告......
我对检查部分一无所知。我需要一个数据库吗?
if (textInput== ??existing entry??)
alert ("you have entered that output number for that output type");
// quit the codes below or something?
答案 0 :(得分:4)
function isExist(newEntry){
return Array.from($('tr[id*=output_newrow]'))
.some(element => $('td:nth(2)', $(element)).html() === newEntry );
}
newEntry
是要添加的输入文本的值
然后:
$('.add').click(function () {
textInput = "";
$('.TextInput').empty();
textInput = $(this).prev('.TextInput').val();
if(isExist(textInput)){
alert("you have entered that output number for that output type")
}else{
//.....insert code
}
})
http://jsfiddle.net/abdennour/MKfLU/27/
“但它适用于不同的选择选项,但同样的输入数字...我可以做isExist(textInput)AND(类型)吗?” 如果你想在测试中嵌入类型:
function isExistx(newEntry,outtype){
return Array.from($('tr[id*=output_newrow]')).some( el =>
( $('td:nth(1)',$(el)).html() === outtype ) && ($('td:nth(2)',$(el)).html() === newEntry)
);
}
然后:
if(isExistx(textInput,type)){
alert('you have entered that output number for that output type')
}else {
$('#status_table tr:last').after(str);
}
答案 1 :(得分:3)
尝试
var flag = false;
$('#status_table tbody').find('tr').each(function(){
var $this = $(this);
if(textInput == $('td:eq(2)', $this).text() && type == $('td:eq(1)', $this).text()){
flag = true;
return false;
}
});
if(flag){
alert('exists');
return;
}
演示:Fiddle
答案 2 :(得分:2)
在添加<td>
时,您可以使用类型和数字的组合为其添加data-unique-identifier
属性。
$td.data('unique-identifer', 'type: ' + type + 'number: ' + number);
然后,在添加另一行之前,可以使用jQuery查看是否存在与相同唯一标识符匹配的行。
var uid = 'type: ' + type + 'number: ' + number;
if ($('[data-unique-identifer=' + uid + ']').length > 0) {
// already exists
}
或者你可以将信息保存在DOM之外,只需维护你添加的信息的javascript数组。
添加新行时:
myExistingRows.push({
type: type,
number: number
});
并在添加之前查看是否已存在行:
function doesRowExist(type, number) {
for (var index = 0; index < myExistingRows.length; index++) {
var row = myExistingRows[index];
if (row.type === type && row.number === number) {
return true;
}
}
return false;
)