check item in array, if there print specific text in JS/HTML

93 Views Asked by At

So I have worked in IT for about 7 years now, however I never got into a position that involved a ton of coding. I like it to code, but am just a hobbyist at the moment, just to give you some understanding of my level of coding proficiency.

I am trying to create an HTML page that has some text before an input box, followed by a button. The button will perform a function on click, I want this function to take the input and run it against an array, if the item exists in the array, then I want it to print a specific message. This message is different for each item in the array.

To give you an idea of what I am doing, this is for my Dungeons and Dragons game, running the curse of strahd there is a part where a sequence of card draws are made to help you through the adventure. so say they draw a card, I put the word "Avenger" in the input box, it does exist in the array, I then want it to print "The treasure lies in a dragons house, in hands once clean, now corrupted." I know i could just write it all down, but i thought I would make a fun project of it. I have cobbled together what I think should work however when I press the button nothing happens.

<script>
    var LowCards ["avenger", "paladin",}

the array is there, populated with about 40 names, avenger, paladin, warrior, rogue, enchanter etc.

    function CARD1()
    {
        var card1 = document.getElementByID('card1').value;
        if(CARD1.indexOf("avenger") !== -1){
        alert("The treasure lies in a dragons house, in hands once clean, now corrupted.")
        } else if{CARD1.indexOf("paladin") !== -1){
        alert("I see a sleeping prince, a servant of light and the brother of darkness. The treasure lies 
        with him.")
        }

etc, etc, through the whole list of 40 until this last statement which says, if it isnt there tell them it doesnt exist.

        else{
        alert("Value does not exists!")
        }
    }
</script>

So the function is declared before the body, in the body I try to pull the fucntion with the button

<input type="text" id="card1" name="card1"=>Enter the name of the first card drawn</input>
<button onclick="CARD1();">Submit</button>
</p>
2

There are 2 best solutions below

2
DCR On BEST ANSWER

Your logic is a little messed up. indexOf will return positive number whenever the input is found in the array. Thus only the first if statement will get executed. The map function is a good way to go but if you are just starting out basic programming will do the trick. Objects have keys and attributes. Consider:

var LowCards = {avenger:"The treasure lies in a dragons house, in hands once
                clean, now corrupted.", paladin:"I see a sleeping prince, a 
                servant of light and the brother of darkness. The treasure 
                lies with him."};

avenger and paladin are keys and the associated text in quotes are the attributes.

var keys = Object.keys(LowCards);  
will get create an array called keys with each key.

var LowCards ={avenger:"The treasure lies in a dragons house, in hands once clean, now corrupted.", paladin:"I see a sleeping prince, a servant of light and the brother of darkness. The treasure lies with him."};


    function CARD1()
    {
        var card1 = document.getElementById('card1').value;        
        var keys = Object.keys(LowCards);  
        var len = keys.length;
        
        
        for(let i = 0; i< len;i++){           
           if (card1 == keys[i]) {
              alert(LowCards[card1]);
              return;
           }   
        }
        
        alert("the value does not exist");
        return;
        
        
        
    }
<input type="text" id="card1" name="card1">Enter the name of the first card drawn
<button onclick="CARD1();">Submit</button>

2
dmitrydwhite On

Let's double check your HTML:

  <p>Type a card name and click submit</p> <!-- Make sure you have opening and closing tags -->
  <input type="text" id="card1" name="card1" /> <!-- Inputs are self-closing -->
  <button type="button" onclick="CARD1();">Submit</button> <!-- Give your button a type "button" to prevent any wacky default behavior -->

Another question: are you seeing console errors? Especially I would suspect that you would see

Uncaught TypeError: CARD1.indexOf is not a function

If you're seeing that, I suspect that your problem is that you're declaring the variable name to be card1, but you're checking CARD1.indexOf. (CAsing is imPORtant )

Next, you've got a little confusion around how you're using indexOf. Basically, using indexOf is asking the question, "At what index is the value I'm passing found in the Array I'm calling off of?" So, for example, ["avenger", "paladin"].indexOf("avenger") will always return 0 (the zeroeth position in the Array).

I would suggest you graduate from your if/else chain up to a more advanced JS (and really programming in general) concept, the Map--which in JS is basically just an object. Here's a simple solution:

var textReceived = document.getElementById('card1').value;
// The variable name "textReceived" is more descriptive than "card1"
const cardTextMap = {
  avenger: 'The treasure lies in a dragons house, in hands once clean, now corrupted.',
  paladin: 'I see a sleeping prince, a servant of light and the brother of darkness. The treasure lies with him.',
  // ... all the other cards
};

// Now we'll check to see if the card name is found in the Object named "cardTextMap".
// We use square bracket notation instead of dot notation, because using square bracket
// allows us to pass a dynamic value as a key, i.e. the value of "textReceived"
if (cardTextMap[textReceived]) {
  // If we found a value inside of cardTextMap that matched what was typed,
  // e.g. cardTextMap.avenger (which can also be written `cardTextMap["avenger"]`),
  // then alert that value
  alert(cardTextMap[textReceived]);
} else {
  // If the user typed something that's not in the Map,
  // then cardTextMap[textReceived] will evaluate to `undefined` which
  // is "falsey" in JavaScript, so we'll fall into this else block:
  alert('Could not find the card you typed');
}