skip to Main Content

I have an input textbox for users to search for another user by either first name, Last Name or full name and if name found, either hide the non-match one or color the found one.
My structure looks

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

const usersInRow = $(this).find('td').eq(6);
const users = usersInRow[0].innerText;
const userFound = users.substring(users.contains(userSerach)).toLowerCase();
if (userFound.length > 0) {
  $(userFound).css('color', 'red');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control" id="userId" placeholder="Search by user's name" value="">
<dl>
  <dt>ADMINISTRATORs (<span style="color: red;">3</span>)</dt>
  <dd>Louis,Edward</dd>
  <dd>Gary,Anthony</dd>
  <dd>Carlson,Matthew</dd>
</dl>

2

Answers


  1. What I understood looking at your code is that you want to search matching text into <dd> and want to highlight them.

    You can do it like below:

    $('#userId').keyup(function() {
      userSerach = ($("#userId").val() || '').toLowerCase();
      if (userSerach != '') {
        $('dl dd').each(function() {
          if ($(this).text().toLowerCase().indexOf(userSerach) > -1) {
            $(this).css('color', 'red');
          } else {
            $(this).css('color', 'black');
          }
        });
      } else {
        $('dd').css('color', 'black');
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" class="form-control" id="userId" placeholder="Search by user's name" value="">
    <dl>
      <dt>ADMINISTRATORs</dt>
      <dd>Louis,Edward</dd>
      <dd>Gary,Anthony</dd>
      <dd>Carlson,Matthew</dd>
    </dl>
    Login or Signup to reply.
  2. I used pure js and css, this may help you

    const input = document.getElementById('userId');
    const names = document.querySelectorAll('.name');
    
    input.onkeyup = function() {
        const value = this.value;
        names.forEach(n=>{
            const res =n.innerText.toLowerCase().includes(value) && value!='';
            n.classList.toggle('active',res)
        })
    }
    .active{
        color:red;
    }
    <input type="text" class="form-control" id="userId" placeholder="Search by user's name" value="">
    <dl>
        <dt>
            ADMINISTRATORs (<span style="color: red;">3</span>
            )
        </dt>
        <dd class='name'>Louis,Edward</dd>
        <dd class='name'>Gary,Anthony</dd>
        <dd class='name'>Carlson,Matthew</dd>
    </dl>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search