简体   繁体   中英

How to check for a value in array with Javascript with text input

I would like to check for a value in an array using a text input. If the value is present in the array, I want to show the user a text.

My question: Is there a way to don't use jQuery?

Here is what I got up to now: http://jsfiddle.net/t8r5eLxb/

$(document).ready(function(){
    var recherche ="";
    var liste = ["Ariat", "Wrangler", "turtles"];
    var sorted = [];
    for (var i = 0; i < liste.length; i++) {
        sorted.push(liste[i].toLowerCase());
    }
    sorted.sort();


$("#filter").keyup(function(){
    var recherche = $(this).val();

// Résultat
var resultat = (sorted.indexOf(recherche.toLowerCase()) > -1);

    if( $(resultat).text().search(new RegExp(filter, "i")) < 0 ){
        $('#resultat').fadeIn();
    }
    else{
        $('#resultat').fadeOut();
    } 

});
});

<form id="live-search" action="" method="post">
   <fieldset>
       <input type="text" class="text-input" id="filter" value="" />
   </fieldset>
</form>
<div id="resultat">Vrai</div>

Sure you can avoid jQuery, which is also written in pure JavaScript.

Since you only need to check if input text matches any string in the predefined array, you can bypass the sort operation and go directly to comparison.

There are some event handler existed in pure JS, like onkeyup , which is pretty handy for input retrieval.

Fade in and out effect can be rendered with CSS transition and opacity, as shown in the <style> part. The JS function assign different classNames to the div according to the match result.

The follow code has been tested in Chrome browser and should meet your requirement.

<!DOCTYPE html>
<html>
<head>
    <style>
        .fadeOut {opacity: 0; color:red;}
        .fadeIn {opacity: 1; color:green;}
        #resultat {
            font-size: 20px;
            -webkit-transition: opacity 1s ease-in-out;
            -moz-transition: opacity 1s ease-in-out;
            -o-transition: opacity 1s ease-in-out;
            -ms-transition: opacity 1s ease-in-out;
            transition: opacity 1s ease-in-out;}
    </style>
</head>
<body>
    <form id="live-search" action="" method="post">
        <fieldset>
            <input type="text" id="filter" value="">
        </fieldset>
    </form>
    <div id="resultat" class="fadeOut">Vrai</div>
    <script>
        function test(){
            var liste = ["Ariat", "Wrangler", "turtles"];
            var filter = document.getElementById('filter');
            var resultat = document.getElementById('resultat');

            filter.onkeyup = function(event){
                var recherche = event.target.value;
                var match = false;

                for(var i in liste){
                    if(liste[i] == recherche) match = true;
                }

                if(match){
                    resultat.className = 'fadeIn';
                }
                else{
                    resultat.className = 'fadeOut';
                }
            };
        };
        test();
    </script>
</body>
</html>

The <form> tag in this demo, actually, is not necessary. You can just keep <input> and <div> tags and get the same result.

I've re-written the jQuery lines of your code in vanilla JavaScript . Please see the comments for what is happening. // ... means I've skipped ahead

function node_show(node) { // $(node).fadeIn, without fade :(
    node.style.display = 'block';
}

function node_hide(node) { // $(node).fadeOut, without fade :(
    node.style.display = 'none';
}

window.addEventListener('load', function (e) { // $(document).ready
    document.getElementById('filter') // $("#filter")
        .addEventListener('keyup', function (e) { // .keyup
            var recherche = this.value; // $(this).val();
            // ...
                node_show(document.getElementById('resultat'));
            // ...
                node_hide(document.getElementById('resultat'));
            // ...
        });
});

Well I believe I got you right and this how I interpreted your question. So I will just write few lines of codes how i would have gone about that.

 window.addEventListerner("DOMContentLoaded", (e)=>{ let itemsArr = ["subaru", "rangerover", "bmw", "voxwagen"]; let userInput = document.querySelector("input[type=text]").value; if(itemsArr.includes(userInput)){ console.log ("my text to user") } });
 <html> <body> <form> <input type="text"> </form> </body> <script src="myscript.js"> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM