0

Im learning Javascript now and I got a question that's been bugging me!

So, all I needed to do here is to type a color on this input box, click the button and change the headline to the color typed only if that typed color is in the array specified in the variable.

My code is half working... it does check if whatever color typed is inside the array, but the alert button pops up each time, is there a way to make the alert pop up only if the color typed isn't in the array please?

Working code: https://codepen.io/anon/pen/ddPWLP

Javascript code:

const myHeading = document.getElementById('myHeading');
const myButton = document.getElementById('myButton');
const myTextInput = document.getElementById('myTextInput');

var colors = ["red", "black", "blue"];

myButton.addEventListener('click', () => {
    for (var i=0; i<colors.length; i++){
        if (myTextInput.value === colors[i]){
            myHeading.style.color = myTextInput.value
        } else {
            alert("no color")
        }
    }

});
2
  • use a boolean variable and set it to true if a matching color has been found. check at the end of the for loop if the value of the bool is true. If it's false (the initial value), only then do the alert() Commented Jan 30, 2018 at 14:38
  • consider using a hash (an object) instead of an array for the colors. That way you don't have to search the entire array. Commented Jan 30, 2018 at 14:39

1 Answer 1

4

Don't do it inside the loop. Use a variable to flag when you find a match, and then after the loop check that flag and display the alert accordingly. Try this:

myButton.addEventListener('click', () => {
  var found = false;
  for (var i = 0; i < colors.length; i++) {
    if (myTextInput.value === colors[i]) {
      myHeading.style.color = myTextInput.value
      found = true;
    }
  }
  if (!found)
    alert("no color");
});

By the way, you don't need a loop for that. You can simply use the indexOf() methods. If the value exists in the array, it returns its index, otherwise it returns -1. Try this:

myButton.addEventListener('click', () => {
  if (colors.indexOf(myTextInput.value) > -1)
    myHeading.style.color = myTextInput.value
  else
    alert("no color");
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.