1

I am beginning Javascript learning, and am stumped on my first function. Spelling it out for my own sake, here is what I am try to achieve:
declare variables: color and primary
set color equal to the id "color" and grab the input value
set primary equal to one of two strings based on if color's value is either red, blue, or yellow
display primary in the p with id "answer"

I don't get a output. I suspect I should be using something in place of .value, and maybe the or statement is not correct. Would someone please give me a few pointers? I would greatly appreciate it. Here is the code:

<div>
Color:<input id="color" />
<p>Primary Color?</p>
<button onclick="myFunction1()">Click</button>
<p id="answer"></p>

<script>
function myFunction1()
{
   var color,primary;
   color=document.getElementById("color").value;
   primary=(color="red"||"blue"||"yellow")?"It is a primary color":"Not a primary color";
   document.getElementById("answer").innerHTML=primary;
}
</script>

</div>

3 Answers 3

4

Two problems.

  1. = is an assignment. === is a comparison. (== is also a comparison but does type conversion).
  2. You need a complete expression on each side of your ORs

Such:

(color === "red" || color === "blue" || color === "yellow")

Alternatively, you could just search an array:

(["red", "blue", "yellow"].indexOf(color) !== -1)
Sign up to request clarification or add additional context in comments.

1 Comment

Its important to note that not all browsers support indexOf for arrays. However the MDN documentation supplies an add-in for this feature.
1

You can't use || to chain values to compare, it chains conditions. You need to compare the variable to each value:

color == "red" || color == "blue" || color == "yellow"

Comments

1

The ternary expression must evaluate each condition using ==, the = operator is used for assignment.

primary=(color=="red"|| color=="blue"||color=="yellow")?"It is a primary color":"Not a primary color";

You may also want to consider lowercasing the supplied value for a case insensitive comparison:

color=document.getElementById("color").value.toLowerCase();

JS Fiddle: http://jsfiddle.net/K3KUK/

1 Comment

Consider using the === instead of the == because it's more easy to reason about?

Your Answer

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