Like a tag on a table element with jQuery?

Asked

Viewed 211 times

4

I have a simple table:

table {
  border-collapse: collapse;
}

table tr td {
  border: 1px solid #000;
}

mark {
  background: yellow;
}
<table width="300px" border="1px" bordercolor="#FF0000">
  <tbody id="qtdPrecos">
    <tr id="precos">
      <td class="pointer fmp-td">R$ 92.4</td>
      <td class="pointer fmp-td">R$ 137.48</td>
      <td class="pointer fmp-td">R$ 108.27</td>
      <td class="pointer fmp-td">R$ 129.25</td>
    </tr>
  </tbody>
</table>

How do I insert the tag <mark></mark> in the <td> that has the lowest value with jQuery?

Thus:

<td class="pointer fmp-td"><mark>R$ 92.4</mark></td>
  • First, identify the cell with the lowest value. Have you already achieved this? If yes, post the code. If not, describe how you think it’s done.

  • I couldn’t. I thought I’d list all the <td> who are inside the <tr> with the id #precos using the $.each jQuery then take the one that has the lowest value using the Math.min.apply(Math, variavel). Then add the tag and replace the <td>. But I couldn’t

  • The idea sounds right. Can you still post this code you tried to do? It will help you identify exactly what your mistake was.

  • I could only find the lowest value: https://jsfiddle.net/newtech/gr9xn8as/

  • Right. Now you go through all the elements td, checks which has the value equal to the minimum and adds the tag mark.

  • Question: and if there are two equal prices, both should be marked or what would be the selection criteria?

  • There will never be two equal prices. I group the same values before listing in the table

  • 1

    You could edit the title of the question @user, you’re confused.

Show 3 more comments

4 answers

4


The idea here is:

  • Use ES6 features as Operator spread and Arrow Function to return an array
  • Use the Array#map to return only the contents of tds
  • Apply the regular expression /[0-9.]/g to capture only the numerical value
  • Finally find the smallest and use the wrapInner jQuery to create markup

const tds = [...document.getElementsByTagName('td')].map(item => Number(item.innerHTML.match(/[0-9.]/g).join('')));
const menor = Math.min.apply(Math, tds);

$('td').each(function() {
  if ($(this).html().indexOf(menor) > -1) {
    const aux = $(this).html();
    $(this).html('').wrapInner('<mark>' + aux + '</mark>');
  }
});
table {
  border-collapse: collapse;
}

table tr td {
  border: 1px solid #000;
}

mark {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="300px" border="1px" bordercolor="#FF0000">
  <tbody id="qtdPrecos">
    <tr id="precos">
      <td class="pointer fmp-td">R$ 92.4</td>
      <td class="pointer fmp-td">R$ 137.48</td>
      <td class="pointer fmp-td">R$ 108.27</td>
      <td class="pointer fmp-td">R$ 129.25</td>
    </tr>
  </tbody>
</table>

  • How can I know which features ES6 I can already use in production?

  • 1

    Many of the features are already supported by the new browsers without using a @Rafaelacioly transpiler. We can look here and here to see the compatibility.

2

Below is code commented with each step to mark the lowest value with the mark.

$(function() {

  function markMinValue() {
    var pricesTd = $('td', 'table #qtdPrecos #precos'),
      pricesValue = [],
      minValue,
      indexMinValue;

    // Percorre as linhas da tabela com preços
    $.each(pricesTd, function(indice, element) {
      // Armazena o valor de cada uma em uma variável temporária
      var value = $(element).text().replace('R$ ', '') * 1;
      // Adiciona no array o valor
      pricesValue.push(value);
    });

    // Busca o menor valor
    minValue = Math.min.apply(null, pricesValue);

    // Encontra o indice do menor valor
    indexMinValue = pricesValue.indexOf(minValue);

    // Marca o item com menor valor pelo indice encontrado
    $(pricesTd[indexMinValue]).wrapInner('<mark></mark>');

  }

  // Executa a função para marcar o item de menor valor
  markMinValue();

});
table {
  border-collapse: collapse;
}

table tr td {
  border: 1px solid #000;
}

mark {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table width="300px" border="1px" bordercolor="#FF0000">
  <tbody id="qtdPrecos">
    <tr id="precos">
      <td class="pointer fmp-td">R$ 92.4</td>
      <td class="pointer fmp-td">R$ 137.48</td>
      <td class="pointer fmp-td">R$ 108.27</td>
      <td class="pointer fmp-td">R$ 129.25</td>
    </tr>
  </tbody>
</table>

2

I saw that already answered the question, but I am contributing with another solution of the problem, my answer was based on solutions found here: Find the smallest value of a table Row using javascript .

//Percorre as TDS da table e monta um ARRAY
var valoresNaTd = $('#qtdPrecos tr td').map(function() {
  var valor = $(this).text().substr(2);
  return valor;
}).get();

//Localiza o valor mínimo no array
var valorMinimo = Math.min.apply(Math, valoresNaTd);

//Coloca o mark na TD de menor valor
$('#qtdPrecos tr td').filter(function() {
  return $(this).text().substr(2) == valorMinimo;
}).wrapInner('<mark></mark>');
table {
  border-collapse: collapse;
}

table tr td {
  border: 1px solid #000;
}

mark {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="300px" border="1px" bordercolor="#FF0000">
  <tbody id="qtdPrecos">
    <tr id="precos">
      <td class="pointer fmp-td">R$ 92.4</td>
      <td class="pointer fmp-td">R$ 137.48</td>
      <td class="pointer fmp-td">R$ 108.27</td>
      <td class="pointer fmp-td">R$ 129.25</td>
    </tr>
  </tbody>
</table>

1

Let’s separate by steps what must be done:

  1. Take all values within each td.
  2. Put them in order from minor to major.
  3. Take the lowest value element and insert the tag <mark></mark> in it.

Step 1:

Taking all the elements:

$('#precos td.pointer');

Step 2:

Set elements in order according to the value within the HTML, for this we can use the function sort() that performs a loop taking 2 in 2 elements and comparing between them:

var values = $('#precos td.pointer').sort(function(current, next) {
    // Substitui a string R$ por "vazio" e pega apenas os 
    // valore dentro do HTML e transforma em números.
    var one = parseFloat(current.innerHTML.replace('R$', ''));
    var two = parseFloat(next.innerHTML.replace('R$', ''));

    // Verifica se o valor atual é maior ou menor que o próximo
    if (one < two) return -1;
    return 1;
});

Now the variable values has all elements in descending order (smaller to larger), and so we can simply take the first element of values that will always be the greatest and change the HTML

$(values[0]).html('<mark>'+values[0].innerHTML+'</mark>');

See below the code working:

var values = $('#precos td.pointer').sort(function(current, next) {
    // Pega apenas os valore dentro do HTML e transforma em números.
    var one = parseFloat(current.innerHTML.replace('R$', ''));
    var two = parseFloat(next.innerHTML.replace('R$', ''));

    // Verifica se o valor atual é maior ou menor que o próximo
    if (one < two) return -1;
    return 1;
});

$(values[0]).html('<mark>'+values[0].innerHTML+'</mark>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="300px" border="1px" bordercolor="#FF0000">
   <tbody id="qtdPrecos">
      <tr id="precos">
         <td class="pointer fmp-td">R$ 92.4</td>
         <td class="pointer fmp-td">R$ 137.48</td>
         <td class="pointer fmp-td">R$ 108.27</td>
         <td class="pointer fmp-td">R$ 129.25</td>
      </tr>
   </tbody>
</table>

  • All I had to do was edit the explanation there "ascending order (largest to smallest)", in case the values became from the smallest to the largest now.

Browser other questions tagged

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