Joysofyz Joysofyz - 6 months ago 14
HTML Question

Grab Only Numeric Number from Specific Text Paragraph During Mouseover/Hovering

I am having an issue of detecting numbers from a html string paragraph.
Let me start with an overview of the html page.


  1. 1 table consisting only numbers

  2. 1 paragraph consisting alphabets, numbers and symbols



What I am trying to do is, when user mouseover or hover on any number in the paragraph, the same number in the table will have a change in style (maybe highlighted).

The question is, how do I extract the number from the paragraph using jQuery by just mouseover or hover?

I have been thinking of adding span tag to each numeric value in the paragraph so that I can maybe use `$(this).find('span').text(...) to match with the cells of the table afterwards.

Anyone give me some idea how to start the detection? Tqvm!

Answer

$(document).ready(function(){
  var tds = $('td');
  
  $('span').on('mouseenter ', function(){
    var text = $(this).text();
    $.each(tds, function(i, l){
      var tmp = tds.eq(i).text();
      if (tmp == text) {
        tds.eq(i).addClass('highlight');
      } else {
        tds.eq(i).removeClass('highlight');
      }
    });
  });

  $('span').on('mouseleave', function(){
    $.each(tds, function(i, l){
      tds.eq(i).removeClass('highlight');
    });
  });
  
});
.highlight{
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
    <tr>
    <td>4</td>
    <td>5</td>
    <td>6</td>
  </tr>
</table>

<p>
Lorem <span>1</span> Ipsum <span>2</span> Dolor <span>3</span>
</p>
</p>