2013-02-19 137 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