Filter elements according to keystroke Jquery / Javascript

0

I have an input that the user types the filter you want, every key pressed I want to make a filter, if the typed text contains in the array I want # div_1 to be displayed otherwise I want # div_2 to be displayed, to help?

$('#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();
        }     

    });
    
asked by anonymous 06.06.2018 / 20:52

1 answer

0

If I understood your intent correctly, I think you're just missing a 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>
    
06.06.2018 / 21:22