Scooter Daraf Scooter Daraf - 5 months ago 8
HTML Question

Find matched letter from each word in javascript array

I have an array in javascript like that :

var books = ['spring','last night','sweet heart','the sky','tomorrow'] ;


I have textarea

<textarea id="text" name="textpreview" class="text"></textarea>


So what I want is when I enter letter
s
then I will get two suggestions books just the first word not the second word I mean not
sky
Just
spring
and
sweet heart
.

I will get two spans

<textarea id="text" name="textpreview" class="text"></textarea>
<span>spring</span>
<span>sweet heart</span>


If I type again after
s
the
p
letter like
sp
in textarea then I will get just
spring


<textarea id="text" name="textpreview" class="text"></textarea>
<span>spring</span>


and so on .

If I type
n
I will get nothing.

If I type
t
I will get
tomorrow
and
the sky


Hope it can be done . Thanks for your support .

Answer

This help you :

<html>
<head>
    <title></title>
</head>
    <body>
        <textarea id="text" name="textpreview"  class="text"></textarea>
        <p id="x"></p>
        <script>
            var x = document.getElementById("x");
            var books = ['spring','last night','sweet heart','the sky','tomorrow'];
            var txt = document.getElementById("text");
            txt.onkeyup = function(event) {
                var value = txt.value;
                var str = "";
                var patt = new RegExp("^"+value);
                for(var i=0;i<books.length;i++) {
                    if (patt.test(books[i]))
                        str+= books[i] + "<br>";
                }
                if(value == "")
                    str = "";
                x.innerHTML = str;
            }
        </script>
    </body>
</html>