简体   繁体   中英

Append on table if data not exist jQuery

I have a code that appends a row data. What I want is remind the user if they will add details that already exist in the table.

JSFIDDLE

$('#try').click(function() {   
var text = document.getElementById('add');
    if($('#test td:contains("'+text.value+'")') == true) {
        alert('not allowed');
    }else{   
        $('#test').append('<tr><td>' + text.value + '</td></tr>');
    }
text.value = '';    
});

What's happening in my code is, it doesn't filter on line :contains .

What is wrong in my code?

To start with, you must test the length of a jQuery object to know if there's an element in the DOM :

if ($('#test td:contains("'+text.value+'")').length) {

But your code will fail if text.value contains anything that breaks the selector, for example quotes, so you'd better directly test the content with filter :

var elems = $('#test td').filter(function(){
     return this.innerHTML.indexOf(text.value) !== -1
});
if (elems.length) {

Fixed fiddle

It's possible that what you want isn't in fact, to test if the cell "contains" the string, but if it contains only that string (ie, you want to allow "test 21" and "test" when there's already "test 2" ). To do that, you may filter this way :

var elems = $('#test td').filter(function(){
     return $(this).text()===text.value
});
if (elems.length) {

Fiddle

Try:

$('#try').click(function () {
    var test = $("#add").val();
    var sample = $("#add2").val();
    var flag = 0;
    $("#test").find("tr").each(function () { //iterate through rows
        var td1 = $(this).find("td:eq(0)").text(); //get value of first td in row
        var td2 = $(this).find("td:eq(1)").text(); //get value of second td in row
        if ((test == td1) && (sample == td2)) { //compare if test = td1 AND sample = td2
            flag = 1; //raise flag if yes
        }
    });
    if (flag == 1) {
        alert('not allowed');
    } else {
        $('#test').append('<tr><td>' + test + '</td><td>' + sample + '</td></tr>');
    }
    $("#add").val("");
    $("#add2").val("");
});

Updated fiddle here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM