Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

Reset search results using JavaScript when we click on any button (event)

In this, the searched results will show as in maroon colour and bold. I want to reset the search results when we click on any button (A-Z) means when we click on any other button let say B and come back to A, it is still showing as in maroon colour and bold. Can anyone please help me to reset the search results when we click on any button event (It should show as a normal text like other values in this case.)?

Result of search

Result after clicking on button B and come back to A

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js'></script><script>$(document).ready(function(){
  // ===================================
  
  // Filter per data-key="value"
  $.fn.filterData = function(key, value) {
    return this.filter(function() {
      return $(this).data(key) == value;
    });
  };
  // :contains case-insensitive
  $.expr[":"].contains = $.expr.createPseudo(function(arg) {
    return function( elem ) {
      return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
  });
  // reset
    function resetAlphabet(ab, letter) {
    var starter = (letter == '') ? $(ab).children('button').first().data('value') : letter;
    var lettercode = starter.charCodeAt(0);    
    if ((lettercode >= 65) && (lettercode <= 90) && (ab != '')) {
      activateLetter($(ab).children('button').filterData("value", starter));
    }
  }
  // active div letter
  function activateLetter(ellet) {
    var thisletter = $(ellet).data('value');
    window.scrollTo(0, 0);
    $(ellet).addClass('active');
    $(ellet).siblings().removeClass('active');
    if (!$("#" + thisletter).hasClass('active')) {
      $(source).children('div').removeClass('active');
      $("#" + $(ellet).data('value')).addClass('active');
    }
  }
  // delay 
  function delay(callback, ms) {
    var timer = 0;
    return function() {
      var context = this, args = arguments;
      clearTimeout(timer);
      timer = setTimeout(function () {
        callback.apply(context, args);
      }, ms || 0);
    };
  }

  // Startup
    var $ts = $('.text-search');
    var source = '';
    var alphabet = '';
  var searchtitle = '';
  var searchin = '';
  var lbl = '';
    var $elemsfound;
  var offset = 0;
          
    if ($ts.length > 0) {       
        alphabet = $ts.data('alphabet') || alphabet;
        source = $ts.data('source') || source;
    searchtitle = $ts.data('searchtitle') || searchtitle;
    lbl = $("label[for='" + $ts.attr('id') + "']");
    offset = $ts.data('offset') || 0;
    offset = ((searchtitle != '') && offset == 0)  ? parseInt($(searchtitle).css('marginTop')) : offset;
    
        if ($(source).length == 1) {                         
      if (alphabet != '') {
        var $ab = $(alphabet);
        if ($ab.length > 0) {       
          var alphaletters = $(source).children('div');
          $(alphaletters).css('backgroundColor','').css('border','');
          $ab.html('');
          $(alphaletters).each(function(id, elem){
            $ab.append('<button type="button" data-value="' + $(elem).attr('id') + '">' + $(elem).attr('id') + '</button>' + " | ");
          });               
          $ab.on('click', 'button', function(e){            
            e.preventDefault();
            e.stopPropagation();
            $('.text-search').val('');     
            activateLetter($(this))
          }); 
          resetAlphabet(alphabet, '');
        } else {
          alphabet = '';
          $(source).children('div').addClass('active');
        }
      } else {
        $(source).children('div').addClass('active');
      }
            
            $('body').on('keyup', '.text-search', delay(function(e){
                var sSearch = $(this).val();                
                if (sSearch != '') {                    
          var fl = sSearch.substring(0, 1).toUpperCase();
          $(searchin + '.found').removeClass('found');
          searchin = source + ((alphabet == '') ? '' : ' > div#' + fl) + ((searchtitle == '') ? '' : ' ' + searchtitle);
                    console.log('search for a word: "' + sSearch + '" in "' + searchin + '"');
                    $elemsfound = $(searchin + ':contains("' + sSearch + '")');
          console.log('elementi trovati: ' + $elemsfound.length);
          if ($elemsfound.length > 0) {
            resetAlphabet(alphabet, fl);            
            if (searchtitle != '') {
              var goto = $elemsfound.first().offset().top - offset;
              $("html,body").animate({ scrollTop: goto}, 500 );
            } else {
              console.log('it is a global search')
              $(source).html().replace(sSearch, '<span class="found">' + sSearch + '</span>');
            }
          } else {
            searchin = source + ((alphabet == '') ? '' : ' > div') + ((searchtitle == '') ? '' : ' ' + searchtitle);
            console.log('I DID NOT FIND ANYTHING so I am looking for a word:"' + sSearch + '" in "' + searchin + '"');
            $elemsfound = $(searchin + ':contains("' + sSearch + '")');
            if ($elemsfound.length > 0) {              
              fl = $elemsfound.first().parent().attr('id');
              resetAlphabet(alphabet, fl);
              searchin = source + ((alphabet == '') ? '' : ' > div#' + fl) + ((searchtitle == '') ? '' : ' ' + searchtitle);
              $elemsfound = $(searchin + ':contains("' + sSearch + '")');
              var goto = $elemsfound.first().offset().top - offset;
              console.log(goto);
              $("html,body").animate({ scrollTop: goto}, 500 );
            }
          }  
          $elemsfound.addClass('found');
          if (lbl.length == 1) {lbl.html('Found' + ($elemsfound.length == 1 ? '' : '') + ' ' + $elemsfound.length + ' word' + ($elemsfound.length == 1 ? '' : 's'))};
                } else {
          resetAlphabet(alphabet, '');
          $(searchin).removeClass('found');
          if (lbl.length == 1) {lbl.html('Browse the glossary using this index')}
        }
            }, 500));
        }
    }
});</script>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css'>
body {font-family:helvetica;font-size:14px;}
label  {display:block;}
input[type='text'] 
{width:100%; font-size: 0.9em;
    font-family: helvetica;
    font-style: italic;
    padding: 5px 8px;}
h3 {margin-top:30px;}

.alphabet {display:block; width: 1210px;}
.alphabet button {
  font: inherit;
  color: #398FFF;;
  cursor: pointer;
  display: inline-block;
  position: relative;
  width:40px;
  height:40px;
  line-height:40px;
  font-size:14px;
  margin: 0 -6px 10px -5px;
  border:none;
  background: none;
  padding:0;
  box-shadow:0;
  transition:all 0.3s ease-in-out;
  outline:0;
}
.alphabet:focus {outline:0;}
.alphabet button:hover {background-color:#FFF; font-weight:bold;} 
.alphabet button.active {background-color:#ffa505; font-weight:bold; color:#FFF; box-shadow:0px 0px 0px 2px #FFF inset; }

.glossary {display:block; width:100%; clear:both;}
.glossary .letter {display:none; width: 1115px;; clear:both; text-align:justify; padding-bottom:30px;}
.glossary .letter.active {display:block;}
.glossary h3 {font-size:18px; font-weight:300; margin-bottom:5px;}
.glossary h3.found {font-weight:bold;color: #800020;}
.glossary span.found {background-color:red;}

h3.gloss{
font-family: Helvetica;
    font-size: 1.3rem;
    font-weight: 600;
    }
h3.browse{
    font-size: 1.1rem;
    font-family: helvetica;
    font-weight: 600;
    }
hr{
border-top: 1px solid #C4C4C4;
}
<body>
<div class="container">
  <div class="row">
    <div class="col-lg-4 col-md-6">
      <div class="sticky">
        <input type="text" placeholder="Enter search terms..." id="text-search" class="text-search" data-source="#glossary" data-alphabet="#alphabet" data-searchtitle="h3" data-offset="300"/>

        <h3 class="browse">Browse by alphabet</h3>
        <label for="text-search">Browse the glossary using this index</label>
        <div class="alphabet" id="alphabet">         
        </div>
      </div>
  
      <div class="glossary" id="glossary">
                <div class="letter" id="A">
                    <h3>A</h3></br>
                    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. 
                    
                    <hr>
                    
                    <h3>Actual</h3></br>
                    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. 
                    <hr>
                    <h3>Acurral</h3></br>   
                    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. 
                    <hr>
                    <h3>AD</h3></br> 
                    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. 
                    <hr>
                    
                    
                    
                </div>


                <div class="letter" id="B">
                    
                    <h3>BAC</h3></br>
                        Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. sells goods and services produced by others, e.g. a retailer buying the end product from the food manufacturer.
                    <hr>
                    <h3>Bold</h3></br>
                        Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. 
                    <hr>
                    <h3>BQG</h3></br>
                        Lorem ipsum dolor sit amet, consectetuer adipiscing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Remove class found from all the h3 elements in glossary, since the search is cleared. You can do this with below code -

$('#glossary').find('.letter').find('h3').removeClass('found');

In your code, the changing of letters triggers execution of a if section in activateLetter function, add this code there -

function activateLetter(ellet) {  
    var thisletter = $(ellet).data('value');
    window.scrollTo(0, 0);
    $(ellet).addClass('active');
    $(ellet).siblings().removeClass('active');
    if (!$("#" + thisletter).hasClass('active')) {
      $('#glossary').find('.letter').find('h3').removeClass('found');
      $(source).children('div').removeClass('active');
      $("#" + $(ellet).data('value')).addClass('active');
    }
  }

Working Code -

$(document).ready(function() {
  // Filter per data-key="value"
  $.fn.filterData = function(key, value) {
    return this.filter(function() {
      return $(this).data(key) == value;
    });
  };
  // :contains case-insensitive
  $.expr[":"].contains = $.expr.createPseudo(function(arg) {
    return function(elem) {
      return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
  });
  // reset
  function resetAlphabet(ab, letter) {
    var starter = (letter == '') ? $(ab).children('button').first().data('value') : letter;
    var lettercode = starter.charCodeAt(0);
    if ((lettercode >= 65) && (lettercode <= 90) && (ab != '')) {
      activateLetter($(ab).children('button').filterData("value", starter));
    }
  }
  // active div letter
  function activateLetter(ellet) {
  
    var thisletter = $(ellet).data('value');
    window.scrollTo(0, 0);
    $(ellet).addClass('active');
    $(ellet).siblings().removeClass('active');
    if (!$("#" + thisletter).hasClass('active')) {
      $('#glossary').find('.letter').find('h3').removeClass('found');
      $(source).children('div').removeClass('active');
      $("#" + $(ellet).data('value')).addClass('active');
    }
  }
  // delay 
  function delay(callback, ms) {
    var timer = 0;
    return function() {
      var context = this,
        args = arguments;
      clearTimeout(timer);
      timer = setTimeout(function() {
        callback.apply(context, args);
      }, ms || 0);
    };
  }

  // Startup
  var $ts = $('.text-search');
  var source = '';
  var alphabet = '';
  var searchtitle = '';
  var searchin = '';
  var lbl = '';
  var $elemsfound;
  var offset = 0;

  if ($ts.length > 0) {
    alphabet = $ts.data('alphabet') || alphabet;
    source = $ts.data('source') || source;
    searchtitle = $ts.data('searchtitle') || searchtitle;
    lbl = $("label[for='" + $ts.attr('id') + "']");
    offset = $ts.data('offset') || 0;
    offset = ((searchtitle != '') && offset == 0) ? parseInt($(searchtitle).css('marginTop')) : offset;

    if ($(source).length == 1) {
      if (alphabet != '') {
        var $ab = $(alphabet);
        if ($ab.length > 0) {
          var alphaletters = $(source).children('div');
          $(alphaletters).css('backgroundColor', '').css('border', '');
          $ab.html('');
          $(alphaletters).each(function(id, elem) {
            $ab.append('<button type="button" data-value="' + $(elem).attr('id') + '">' + $(elem).attr('id') + '</button>' + " | ");
          });
          $ab.on('click', 'button', function(e) {
            e.preventDefault();
            e.stopPropagation();
            $('.text-search').val('');
            activateLetter($(this))
          });
          resetAlphabet(alphabet, '');
        } else {
          alphabet = '';
          $(source).children('div').addClass('active');
        }
      } else {
        $(source).children('div').addClass('active');
      }

      $('body').on('keyup', '.text-search', delay(function(e) {
        var sSearch = $(this).val();
        if (sSearch != '') {
          var fl = sSearch.substring(0, 1).toUpperCase();
          $(searchin + '.found').removeClass('found');
          searchin = source + ((alphabet == '') ? '' : ' > div#' + fl) + ((searchtitle == '') ? '' : ' ' + searchtitle);
          console.log('search for a word: "' + sSearch + '" in "' + searchin + '"');
          $elemsfound = $(searchin + ':contains("' + sSearch + '")');
          console.log('elementi trovati: ' + $elemsfound.length);
          if ($elemsfound.length > 0) {
            resetAlphabet(alphabet, fl);
            if (searchtitle != '') {
              var goto = $elemsfound.first().offset().top - offset;
              $("html,body").animate({
                scrollTop: goto
              }, 500);
            } else {
              console.log('it is a global search')
              $(source).html().replace(sSearch, '<span class="found">' + sSearch + '</span>');
            }
          } else {
            searchin = source + ((alphabet == '') ? '' : ' > div') + ((searchtitle == '') ? '' : ' ' + searchtitle);
            console.log('I DID NOT FIND ANYTHING so I am looking for a word:"' + sSearch + '" in "' + searchin + '"');
            $elemsfound = $(searchin + ':contains("' + sSearch + '")');
            if ($elemsfound.length > 0) {
              fl = $elemsfound.first().parent().attr('id');
              resetAlphabet(alphabet, fl);
              searchin = source + ((alphabet == '') ? '' : ' > div#' + fl) + ((searchtitle == '') ? '' : ' ' + searchtitle);
              $elemsfound = $(searchin + ':contains("' + sSearch + '")');
              var goto = $elemsfound.first().offset().top - offset;
              console.log(goto);
              $("html,body").animate({
                scrollTop: goto
              }, 500);
            }
          }
          $elemsfound.addClass('found');
          if (lbl.length == 1) {
            lbl.html('Found' + ($elemsfound.length == 1 ? '' : '') + ' ' + $elemsfound.length + ' word' + ($elemsfound.length == 1 ? '' : 's'))
          };
        } else {
          resetAlphabet(alphabet, '');
          $(searchin).removeClass('found');
          if (lbl.length == 1) {
            lbl.html('Browse the glossary using this index')
          }
        }
      }, 500));
    }
  }
});
body {
  font-family: helvetica;
  font-size: 14px;
}

label {
  display: block;
}

input[type='text'] {
  width: 100%;
  font-size: 0.9em;
  font-family: helvetica;
  font-style: italic;
  padding: 5px 8px;
}

h3 {
  margin-top: 30px;
}

.alphabet {
  display: block;
  width: 1210px;
}

.alphabet button {
  font: inherit;
  color: #398FFF;
  ;
  cursor: pointer;
  display: inline-block;
  position: relative;
  width: 40px;
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  margin: 0 -6px 10px -5px;
  border: none;
  background: none;
  padding: 0;
  box-shadow: 0;
  transition: all 0.3s ease-in-out;
  outline: 0;
}

.alphabet:focus {
  outline: 0;
}

.alphabet button:hover {
  background-color: #FFF;
  font-weight: bold;
}

.alphabet button.active {
  background-color: #ffa505;
  font-weight: bold;
  color: #FFF;
  box-shadow: 0px 0px 0px 2px #FFF inset;
}

.glossary {
  display: block;
  width: 100%;
  clear: both;
}

.glossary .letter {
  display: none;
  width: 1115px;
  ;
  clear: both;
  text-align: justify;
  padding-bottom: 30px;
}

.glossary .letter.active {
  display: block;
}

.glossary h3 {
  font-size: 18px;
  font-weight: 300;
  margin-bottom: 5px;
}

.glossary h3.found {
  font-weight: bold;
  color: #800020;
}

.glossary span.found {
  background-color: red;
}

h3.gloss {
  font-family: Helvetica;
  font-size: 1.3rem;
  font-weight: 600;
}

h3.browse {
  font-size: 1.1rem;
  font-family: helvetica;
  font-weight: 600;
}

hr {
  border-top: 1px solid #C4C4C4;
}
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css'>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js'></script>

<body>
  <div class="container">
    <div class="row">
      <div class="col-lg-4 col-md-6">
        <div class="sticky">
          <input type="text" placeholder="Enter search terms..." id="text-search" class="text-search" data-source="#glossary" data-alphabet="#alphabet" data-searchtitle="h3" data-offset="300" />

          <h3 class="browse">Browse by alphabet</h3>
          <label for="text-search">Browse the glossary using this index</label>
          <div class="alphabet" id="alphabet">
          </div>
        </div>

        <div class="glossary" id="glossary">
          <div class="letter" id="A">
            <h3>A</h3><br>
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

            <hr>

            <h3>Actual</h3><br>
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.
            <hr>
            <h3>Acurral</h3><br>
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.
            <hr>
            <h3>AD</h3><br>
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.
            <hr>



          </div>


          <div class="letter" id="B">

            <h3>BAC</h3><br>
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. sells goods and services produced by others, e.g. a retailer buying the end product from the food manufacturer.
            <hr>
            <h3>Bold</h3><br>
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.
            <hr>
            <h3>BQG</h3><br>
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...