javascriptcsshtml-tablemodal-dialog

Counting cells with a specific class in JavaScript


I have a HTML table and the following script to add a specific class to the cells, depending on their content.

Now, I would like to count only the items with class = active and trigger a modal (autoOpen: true) with the number of those items. Any suggestions?

<script>
$('td').each(function() {
var $this = $(this)
  if ($this.text().match(new RegExp(/^[0-9][A-Z]/)) !== null ) {
    $this.addClass('active');
  }
  if ($this.text().match(new RegExp(/^c[0-9]/)) !== null ) {
    $this.addClass('none');
  }
});
</script>

Solution

  • Here is a more efficient code that returns the number of toggled active cells

    1. cache the regular expression so it is only created once
    2. cache the text so it is only read once
    3. use toggleClass to set the class instead of addClass so we can use the result of the match
    4. use filter so we do not have to run twice
    5. Use jQuery UI to show the modal

    const re1 = /^[0-9][A-Z]/; 
    const re2 = /^c[0-9]/; // 
    
    // Create the dialog once and keep it hidden initially
    const $dialog = $('<div></div>').dialog({
      autoOpen: false, // Do not open immediately
      title: 'Active Element Count',
      modal: true,
      buttons: {
        Ok: function() {
          $(this).dialog('close');
        }
      }
    });
    
    $("#show").on('click', () => {
      const actives = $('td').filter(function() {
        const text = $(this).text();
        const makeActive = text.match(re1) !== null;
        $(this).toggleClass('active', makeActive);
        $(this).toggleClass('null', text.match(re2) !== null);
        return makeActive;
      }).length;
    
      // Update the dialog content and open it
      $dialog.html(`Active elements: ${actives}`);
      $dialog.dialog('open');
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.14.0/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.14.0/themes/base/jquery-ui.css" />
    <table>
      <tbody>
        <tr>
          <td>1A</td>
          <td>c1</td>
          <td>1B</td>
          <td>Something else</td>
          <td>c2</td>
          <td>Here it is not at the start 1A</td>
          <td>c3</td>
        </tr>
      </tbody>
    </table>
    <button type="button" id="show">Click for # active</button>