Search code examples
javascriptjqueryjquery-selectorskeypress

How to use jquery keypress event to hide match or starting class name


First of all Sorry for my poor English. I am not jQuery expert I am trying a real time search query for my app. So I m trying and failing... :(

pls check the code:

$(document).ready(function(){

$( "#test" ).keypress(function( event ) {
        var $gettag = $("#test").val();
        $('p[class^="tr"]').hide(1000); 	                    
        
        //$('p[class^="tr"]').hide(1000);  its works fine
    });
});
<p>Name: <input type="text" id="test" value="Mickey Mouse"></p>

<p>This is a paragraph with little content.</p>
<p class="try">This is another small paragraph.</p>
<p class="tiy">iiiiiiiiiiiiiiiThis is another small paragraph.</p>

I want to hide the class of p what type on the input box. hope can get help. thanks in advance.


Solution

  • If i understood you well, you need to hide the p elements according to the input text.

    So, if i type "try" it should hide the p tag that haves "try" class.

    See if the code below does what you're asking.

    $(function() {
      $("#test").on('keyup', function(event) {
        var value = $("#test").val();
    
        if (value.length > 1) {
        debugger;
          var $element = $('p[class*="' + value + '"]');
    
          if ($element.length == 0) {
            $('p').show(1000);
          } else {
            $element.hide(1000);
          }
        } else {
          $('p').show(1000);
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p>Name: <input type="text" id="test" value="Mickey Mouse"></p>
    
    <p>This is a paragraph with little content.</p>
    <p class="try test">This is another small paragraph.</p>
    <p class="tiy">iiiiiiiiiiiiiiiThis is another small paragraph.</p>