0

I have a problem with my jquery, i need to ask a question in my input if that input is equal to the array then it has to show the text2 with the awnser array but i have no error but it doesnt work.

<section>
        <img id="samen" src="img/samen.svg" alt="samen">
        <img id="klein" src="img/klein.svg" alt="klein">
        <div id="text1">
        <p>Vb.: Professor waarvoor staat html?</p>
        <p>antwoord: HyperText Markup Language</p>
        <input type="text" name="vraag" id="vraag" onkeypress="keyCode(event)" placeholder="Professor, mag ik iets vragen?" required/><br>
        <input id="button" type="submit" name="button" value="wat kan ik stellen?" />
        </div>
        <img id="groot" src="img/groot.svg" alt="groot">
        <div id="text2">
            <p id="arraytext"></p>
        </div>
    </section>  
</main>
<footer>
    <img id="logo" src="img/logo.png" alt="logo">
</footer>
<script>
    var vragen = ["is het gif of jif?"];
    var antwoorden = ["Het is Gif tenzij je de historie kent."];
    var input = $("#vraag").val();
    document.getElementById('button').onclick = function() {
        alert("- Is het gif of jif?"+"\n"+"- ");
    }

    function keyCode(event) {
        var x = event.which || event.keyCode;
            if (x == 13) {
                if(input == vragen){
                    event.preventDefault();
                   $('#text2').css('display', 'inline-block');
                }
                else{
                    event.preventDefault();
                }
            }
    }
</script>

1 Answers1

1

There are a couple of things wrong here. First of all, when you do this:

var input = $("#vraag").val();

You are getting the input value once, and only once, immediately when the page loads. So input will only ever be an empty string. I suspect you meant to get the input value in the function itself:

function keyCode(event) {
    var input = $("#vraag").val();
    // the rest of your code...
}

That way it gets the input when the function executes, instead of when the page loads.

Additionally, this certainly isn't going to work:

if(input == vragen){

because one of these things is a string and the other is an array of strings. An apple will never be the same thing as a basket of apples. Did you mean to check if the array contains that string value? That would be something like this:

if(vragen.includes(input)){

Or, failing the use of .includes(), this:

if(vragen.indexOf(input) > -1){

It's worth noting, of course, that this is only ever going to match the exact string:

"is het gif of jif?"

If the user types anything different, even just using different casing on the letters, then it will no longer be exact and won't match. How you address that depends on the intended functionality and what you're trying to accomplish. "Close enough" can quickly become a pretty complex thing depending on how you define it.

David
  • 208,112
  • 36
  • 198
  • 279