How to prevent add duplicate data in table then stop it using javascript function

I'm trying use this function to prevent the duplicate but only work for prevent not to break action. How to make this function work not only for prevent but for break action too ?

            function AddTipeTruk() {
        var form = $("#formtruk");            
        var contents = {},
            duplicates = false;
        $("#table-custtiptruk td").each(function () {
            var tdContent = $(this).text();
            if (contents[tdContent]) {
                duplicates = true;
                return false;
            }
            contents[tdContent] = true;
        });
        if (duplicates) {
            alert("There were duplicates.");                
        }
        if (form.valid()) {
            var markup = "";
            markup = "<tr><input id='TipTrukId' name='TipTrukId' type='hidden' value='1'><td style='display:none;'><input value='" + 1 + ";" +
                 +$('#JenisTruck option:selected').val() + ";" + $('#Alias').val() + ";" +
                "' name='TipTrukData'/> </td><td class='no'></td><td>" + $('#JenisTruck option:selected').text() + "</td><td>" + $('#Alias').val() + "</td>" +
                   "<td><a href='#' data-toggle='modal' onclick='EditTipTrukRow($(this))'>Edit</a> | <a href='#' onclick='RemoveTipTrukRow($(this));'>Delete</a></td></tr>";
            $("#table-custtiptruk tbody").append(markup);
            updateRowNumberTipTruk();
            $('#modal').modal('hide');
        }                             
    }

Upvotes: 0

Views: 304

Answers (1)

Vijay Maheriya
Vijay Maheriya

Reputation: 1679

You are jumping from inner loop. You need to jump from function too. See below.

$("#table-custtiptruk td").each(function () {
            var tdContent = $(this).text();
            if (contents[tdContent]) {
                duplicates = true;
                return false;
            }
          if(duplicates ==true){
              return !duplicates;
          }
            contents[tdContent] = true;
        });

Upvotes: 1

Related Questions