我正在使用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?
发布于 2013-04-25 04:29:15
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)和(Type)吗?”如果你想在测试中嵌入类型:
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);
}
演示
发布于 2013-04-25 04:18:47
试一试
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
发布于 2013-04-25 04:19:03
在添加<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;
)
https://stackoverflow.com/questions/16206216
复制相似问题