2

How can I avoid having the same data in my table?

Here's the code:

var a = 0;
    $(document).on("change", "#txtInput",function(){
      var inputLength = this.value.length;
      if (inputLength <= 9) { return; }

      $("#contenido").append("<tr><td>" + this.value + "</td></tr>");
      $("p").html('Total Bianuales: ' + (++a));
    });
1
  • What you mean duplicate append data ? input value duplicate ? Commented Sep 12, 2016 at 4:38

2 Answers 2

2

Store the values you've already added, and if the value of the input is already added, don't re-add it.

var a = 0;
var alreadyAdded = [];
$(document).on("change", "#txtInput",function(){
  var inputLength = this.value.length;
  if (inputLength <= 9) { return; }
  if ($.inArray(this.value, alreadyAdded) !== -1) { return; }

  $("#contenido").append("<tr><td>" + this.value + "</td></tr>");
  $("p").html('Total Bianuales: ' + (++a));
  alreadyAdded.push(this.value);
});
Sign up to request clarification or add additional context in comments.

6 Comments

It doesn't allow me to type in the input entry. I mean I can write the ID but it's not added in the table.
im not sure what you mean, can you clarify?
Sure. When I type in the input entry, it doesn't do anything. It's like "it disable itself". But I found out that the problem is with: "alreadyAdded[] = this.value;". When I remove this piece of code, it works normally. I don't how does it affect it. And sorry for my english man, I'm a spanish speaker xD
wasn't that the point? to not add values that have already been added?
Yes sir! But the problem is that it doesn't add any value to the table. It doesn't matter if the table is empty or not.
|
0

Basically, you need to browse the table twice, and check every row. Here a snippet with a example :

//Populate table
for(var i = 0; i<10; i++){
 $('table tbody').append('<tr><td>Row '+i+'</td></tr>');
 $('table tbody').append('<tr><td>Row '+i+'</td></tr>');
 }

//Go along the table twice and check. Remove if the same content.
function cleanTable(){
  for(var i = 0; i<$('table tbody tr').length; i++){
      for(var j = 0; j<$('table tbody tr').length; j++){
      if($('table tbody tr').eq(i).html() == $('table tbody tr').eq(j).html() && i != j){
        $('table tbody tr').eq(j).remove();
      }
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onClick="cleanTable()">Clean</button>

<table>
  <tbody>
  </tbody>
</table>

<button onClick="cleanTable()">Clean</button>

2 Comments

Can I do it without adding a new button?
Yeah of course, just call the cleanTable() function after the loading of the page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.