Change the color of a button by comparing 2 attributes of a list with Jquery

Asked

Viewed 293 times

0

I need to change the color of a button on a product list. However, I receive in a variable another list with the only logged-in user product id. Structure I receive :

[ 2, 7, 18, 21] // are the id of the logged in user products

Based on that, I wanted to know how I can change, using Jquery the color of the button of the list below, as the product id of the list below, equals the list of the structure above.

My list of products is:

<table id="produtos">
            <thead>
                <tr>
                   <th>Nome</th>
                   <th>Usuário</th>
                   <th>Quantidade</th>
               </tr>
            </thead
                <tbody>
                    <c:forEach items="${produtos}" var="p">
                      <tr>
                        <td>${p.nome }</td>
                        <td>${p.usuario.nome }</td>
                        <td>${p.quantidade}</td>
                        <td>
                           <form id="testeForm" action="<c:url value="/atualizaQuantidade"/>" method="post" >
                           <input type="hidden" name="produto.cod" id="cod" value="${p.cod}" />                                                           
       <button type="submit" class="btn btn-primary"></button>            
                                 </form>
                                </div>
                               </td>
                              </tr>
                             </c:forEach>                                        
                         </tbody>
                           </table>

Matching the "Id", change the button color. My table then displays the product name, user name and quantity. I put a button to update, but I wanted it to have a different color if the user responsible for that product was logged in.

Example: user with id 7 logged in, only his products the button was in green color (example), not from it, permancesse the current button color.

Grateful

  • 1

    the content you posted is still too little to elaborate an ideal answer to your question, include your html and js.

  • Leandro, I put what you asked and added more information. Thank you for helping me.

3 answers

2

I usually put the ID on the line. So I can have more control over the DOM.

Whereas if you put the ID in a Hidden field, it takes a lot of manual work to treat the DOM.

See that on the TR of each line I put an ID: produto-ID.

In jQuery I take this ID and shoot the word produto- to use only the ID and compare to the list that is coming.

I hope it will help at least the concept.

$(document).ready(function(){
  // Valores que você recebe
  var listaProdutos = [ 1, 4, 23 ];
  var lista        = $("#listaProdutos").children('tr');
  
  $.each(lista, function(i, v){
      var linha = $(v);
      var idProduto = parseInt(linha.attr('id').replace('produto-', ''));
      if(listaProdutos.indexOf(idProduto) > -1){
        linha.find('span.update').addClass('active');
      }
  });
});
.update{
  font-weight: bolder;
}

.update.active{
  background-color: #00FF00;
  color: #FFFFFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="produtos">
  <thead>
    <tr>
      <th>Nome</th>
      <th>Usuário</th>
      <th>Quantidade</th>
    </tr>
  </thead>
  <tbody id="listaProdutos">
    <tr id="produto-25">
      <td>Diego</td>
      <td>diego.souza</td>
      <td>20</td>
      <td><input type="text"> <span class="update">Atualizar</span></td>
    </tr>
    <tr id="produto-23">
      <td>Diego</td>
      <td>diego.souza</td>
      <td>20</td>
      <td><input type="text"> <span class="update">Atualizar</span></td>
    </tr>
    <tr id="produto-4">
      <td>Diego</td>
      <td>diego.souza</td>
      <td>20</td>
      <td><input type="text"> <span class="update">Atualizar</span></td>
    </tr>
  </tbody>
</table>

  • https://codepen.io/anon/pen/WdvrNE

  • 1

    and to use this: $(this). toggleClass('btn-Success'); ? I’m getting into the discussion as I think I’m going to need this in the future too.

  • This you use when you need to change class on the same object. I think for what you need now it is not necessary. You can use this to open and close a menu, for example.

  • Good evening. Your code worked correctly and as I need. However, I’m adjusting instead of showing the css you added, I put the change of the same button. I caught this part: $(this). toggleClass('btn-Success'); and put in your code but it didn’t work, how could I make it work in your code? Thanks for the help.

  • I don’t quite understand what you need to do with this function. You can explain in more detail?

1

Follow a somewhat generic answer, it would be nice if you edit your question passing more details of your problem and html and javascript structure.

$(document).ready(function(){
  //valores que você recebe
  var listaProdutos = [ 2, 7, 18, 21];
  
$("a[href*='edita?cod=']").each(function(){
      
      //recupera o id do produto pela sua datatable
      var idProduto = parseInt($(this).attr('href').match(/\d+/)[0]);      
      
      //verifica se o id está na lista de produtos
      if(listaProdutos.indexOf(idProduto) >= 0)
      { 
        //manipula o elemento da forma que você quiser       
        $(this).toggleClass('btn-success');
      }
   });
});
@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>id do produto</td>
    <td>usuario</td>
    <td>quantidade</td>
    <td>
      <a href="edita?cod=1" class="btn btn-success btn-xs" title="Editar">
        <span class="glyphicon glyphicon-edit">
      </span>
      </a>
    </td>                                      
  </tr>
  <tr>
    <td>id do produto</td>
    <td>usuario</td>
    <td>quantidade</td>
    <td>
      <a href="edita?cod=2" class="btn btn-success btn-xs" title="Editar">
        <span class="glyphicon glyphicon-edit">
      </span>
      </a>
    </td>                                      
  </tr>
</table>

  • Leandro, I changed how Voce asked. So I have an input field that is filled with the product id. This input has an id="Cod"... I want to compare the value of the list with this field id="Cod", taking the value of the input and making the comparison. If it matches, change the button color. I’m studying your code. Thanks

  • managed to make it work. But instead of using: $("a[href*='edita? Cod=']"). each(Function(), wanted to use input type Hidden’s Cod. How could I modify your suggestion, based on the table I modified?

0

$(document).ready(function(){
  //valores que você recebe
  var listaProdutos = [ 2, 7, 18, 21];
  
$("#cod").each(function(){
      
      //recupera o id do produto pela sua datatable
      var idProduto = parseInt($(this).attr('href').match(/\d+/)[0]);      
      
      //verifica se o id está na lista de produtos
      if(listaProdutos.indexOf(idProduto) >= 0)
      { 
        //manipula o elemento da forma que você quiser       
        $(this).toggleClass('btn-success');
      }
   });
});
@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>id do produto</td>
    <td>usuario</td>
    <td>quantidade</td>
    <td>
      <td>
                       <form id="testeForm" action="<c:url value="/atualizaQuantidade"/>" method="post" >
                       <input type="hidden" name="produto.cod" id="cod" value="${p.cod}" />                                                           
   <button type="submit" class="btn btn-primary"></button>  
    </td>                                      
  </tr>
  <tr>
    <td>id do produto</td>
    <td>usuario</td>
    <td>quantidade</td>
                                     
  </tr>
</table>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.