2013-02-19 151 views
0

我有一个HTML表格,我不希望第二列的值在网格中重复。防止添加重复值html表

这里是我的jQuery:

$('#tb_cartTable tr td:nth-child(2)').each(function() { 
    $ele=$(this).text(); 
if($ele==$productCode) 
    { 
     flag="x"; 
     return false; 
    } 
}); 

if($rowCounter>0 && flag=="x") 
{ 
    alert("Duplicate"); 
} 
else 
{ 
    //... 
} 
+0

是否有任何错误?你能用jsfiddle.net初始化一个完整的例子吗? – 2013-02-19 11:09:07

+0

请发布整个代码... atleast那些你正在定义$ productCode,$ rowcounter,标志 – bipen 2013-02-19 11:10:21

+0

http://jsfiddle.net/rinuthomas90/ZXvQb/这是我的要求,当我点击添加按钮,价值追加到我的jsp页面..我们不能接受重复的值到表。 – 2013-02-19 14:42:23

回答

0

的方法之一将是“地图”细胞的文本具有文本关键字的JavaScript的复杂阵列,然后键进行比较,以量的细胞量。如果比键更多的单元格,则表示存在具有相同文本的单元格。

代码如下:

var allCells = $('#tb_cartTable tr td:nth-child(2)'); 
var textMapping = {}; 
allCells.each(function() { 
    textMapping[$(this).text()] = true; 
}); 

var count = 0; 
for (var text in textMapping) 
    count++; 

if (count !== allCells.length) { 
    alert("found duplicate values"); 
} else { 
    alert("no duplicates found"); 
} 

Live test case

注意以上区分大小写:如果有一个带有“hello”的单元和带有“Hello”的单元,那么这些会被认为是不同的,它会认为没有重复。如果不区分大小写的解决方法是改变行的简单情况:

textMapping[$(this).text().toLowerCase()] = true; 

Updated test case它忽略大小写。

在特定情况下,你可以将所有的普通数组的附加价值,然后使用jQuery​​方法检查数组:

var $addedProductCodes = []; 
$("#button_addItem").click(function(event) 
{ 
    $("span.errorText").remove(); 
    $(".errorField").addClass("notErrorField"); 

     //Change background color of textbox to normal 
     $("#frmRegisterForm :input[type='text']").attr('class','notErrorField'); 
    $hasError = false; 
    $ele = $(event.target); 
    if($ele.is("input[type=button]")) 
    {  
     $td_productCode1=$("#td_productCode1").val(); 
     var index = $.inArray($td_productCode1, $addedProductCodes); 
     if (index >= 0) { 
      alert("You already added this product code in line #" + (index + 1)); 
     } else { 
      $text_productDescription= $("#text_productDescription").val(); 
      $text_basicDealerPrice = $("#text_basicDealerPrice").val(); 
      $('#table_viewContent').append("<tr><td>"+$text_productDescription+"</td><td>"+$td_productCode1+"</td><td><td>"+$text_basicDealerPrice+"</td><td><input type='button' name='deleteRow' id='btn_deleteRow' value='Delete' id='deleteItem' class='deleteItem button-red'></td></tr>");   
      $addedProductCodes.push($td_productCode1); 
     } 
    } 
}); 

Updated fiddle其中添加相同的产品代码会给警觉,并会不插入。

+0

我有三个文本文件和一个添加按钮。每当我点击添加按钮值附加在表中。我想在向表中添加数据时防止重复值...意味着我要比较添加的值和即将添加的值。 – 2013-02-19 14:22:08

+0

对不起,我回答了您的直接问题并发布了代码以检测单元格中的重复值。如果您达到“发现重复值”,则不要添加到表格中,实际上看不到您卡在哪里。 – 2013-02-19 14:47:30

+0

http://jsfiddle.net/rinuthomas90/ZXvQb/当我点击添加按钮时,值附加到我的表(下一行)..我们不能接受重复值(产品代码)到表。如何检查我将添加的附加值和价值..请帮助我 – 2013-02-19 14:48:35