Check if an ID exists on a data-list

1

I'm doing a crud ajax where user chooses a result coming from a data-list to be added to a table (html).

data-list

     <div class="list_details">
       <ul>
        <li id="valor"><img src="..."><p>Nome</p></li>
        <hr>
        <li id="valor"><img src="..."><p>Nome</p></li>
        <hr>
        <li id="valor"><img src="..."><p>Nome</p></li>
        <hr>
      </ul>      
    </div>

Clicking one of the li an event is triggered:

$('.list_details li').on('click',function(){
   if(! $('.tab_aluno').find('tr').attr('id') == $(this).attr('id') ){
      $('.tab_aluno').before('<tr class='+$(this).attr("id")+'><td><img src="'+$(this).find('img').attr('src')+'"></td><td>'+$(this).find('p').text()+'</td><td class="remove">X</td></tr>');  
   }
   $('.list_details').hide();
});

The code to do insert in the tables works, however I want to check in the table itself if the id has already been included. There where the bug catches, at the time of doing this "IF THE ID EXIST IN THE TABLE"

The code above will generate something like:

<table class="tab_aluno">
  <tr id="id">
     <td><img src="..."></td>
     <td>Nome</td>
     <td class='remove'>X</td>
  </tr>
  <tr id="id">
     <td><img src="..."></td>
     <td>Nome</td>
     <td class='remove'>X</td>
  </tr>
</table>

So I'm looking for a logic for if, so it searches all <tr> already in <table> and check if the id has already been included to avoid duplicate results

    
asked by anonymous 19.05.2016 / 18:39

1 answer

1

Is this what you want?

$('.list_details li').on('click',function(){
   var cliked = $(this);
   var found = false;
   $('.tab_aluno tr').each(function(){
     if($(this).attr('id') == cliked.attr('id')) {
         found = true;
         return false; // sair do loop
     }
   });
   if(found) {
      alert('id existe');
   }
   else {
       $('.tab_aluno').before('<tr id="'+cliked.attr("id")+'" class="'+cliked.attr("id")+'"><td><img src="'+cliked.find('img').attr('src')+'"></td><td>'+cliked.find('p').text()+'</td><td>X</td></tr>');  
   }
   $('.list_details_a').hide();
});
    
19.05.2016 / 18:47