skip to Main Content

I am using jquery toggle to show/hide some items and need to display a message when the item is not found. My code below does the toggle hide but I want to show a message when there is nothing to toggle.

const userSearch = ($("#userId").val() || '').toLowerCase();

$('.table tbody tr').find("dl dd").each(function() {
  const userfilter = $(this);
  const userNames = userfilter[0].innerText.toLowerCase();
  const index = userNames.substring(userNames.indexOf(userSearch));
  $(this).toggle(index === userSearch);
});

2

Answers


  1. Check the condition explicitly in an if statement, so you can set a variable to indicate whether you found a match.

    const userSearch = $("#userId").val().toLowerCase();
    
    let foundMatch = false;
    $('.table tbody tr').find("dl dd").each(function() {
      if (this.innerText.toLowerCase().includes(userSearch)) {
        $(this).show();
        foundMatch = true;
      } else {
        $(this).hide();
      }
    });
    
    if (!foundMatch) {
      // display message
    }

    There’s no need for || '' when setting userSearch. .val() always returns a string (unless the selector doesn’t match anything, which shouldn’t happen).

    Login or Signup to reply.
  2. I think you want to just check the length of the items and if it is not greater than zero, show a message.

    Try this

    const userSearch = ($("#userId").val() || '').toLowerCase();
    if(!($('.table tbody tr').find("dl dd").length > 0)) {
      alert('no dd elements');
    } else {
      $('.table tbody tr').find("dl dd").each(function() {
        const userfilter = $(this);
        const userNames = userfilter[0].innerText.toLowerCase();
        const index = userNames.substring(userNames.indexOf(userSearch));
        $(this).toggle(index === userSearch);
      });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search