Filter elements according to typed Jquery/Javascript key

Asked

Viewed 38 times

0

I have an input that the user type the filter you want, every keystroke I want to perform a filter, if the typed text contains in the array I want the #div_1 to be displayed otherwise I want the #div_2 to be displayed, can help me?

$('#term').keyup(function(){    
        var val = $(this).val().toLowerCase(); 
        var elementos = ['japonesa', 'paris 6', 'jundiai'];

        if(elementos.indexOf(val) != -1)    {
            $('#div_1').show();
        }else{
            $('#div_2').show();
        }     

    });
  • And what’s the problem? Didn’t it work? Did it make a mistake? Which one?

1 answer

0


If I understand your intention correctly, I think I’m just missing switch between show and hide:

<html>
    <body>
        <input id="term"></input>
        <div id="div_1"><h1>Div #1</h1></div>
        <div id="div_2"><h1>Div #2</h1></div>

        <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>    
        <script>
        $('#div_1').hide();
        $('#div_2').hide();

        $('#term').keyup(function() {
            var val = $(this).val().toLowerCase();
            var elementos = ['japonesa', 'paris 6', 'jundiai'];

            if (elementos.indexOf(val) != -1) {
                $('#div_1').show();
                $('#div_2').hide();
            } else {
                $('#div_1').hide();
                $('#div_2').show();
            }
        });
        </script>
    </body>
</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.