Reputation: 1
I'm working on a project that will give me a random town wealth depending on what number is randomly generated. Yet whenever I press the "establish township" button, I always get "wealthy". How can I fix my code to enable desired results?
<!DOCTYPE html>
<html>
<body>
<style>
h1 {font-size: 20pt; color: red;}
p {font-size: 17pt; color: blue;}
p2 {font-size: 18pt; color: orange;}
p3 {font-size: 18pt; color: green;}
</style>
<p>This program will create a random town upon the click of a button.</p>
<button onclick="numberdescription()">Establish Township</button>
<br /><br /><br />
<p3 id="random"></p3>
<script>
function numberdescription() {
var num = Math.floor(Math.random() * 3 + 1)
if (num = 1) {
desc = "wealthy";
} else if (num = 2) {
desc = "middle wealth";
} else {
desc = "dirt poor";
}
document.getElementById("random").innerHTML = desc;
}
</script>
</body>
</html>
Upvotes: 0
Views: 49
Reputation: 3451
A single = sign assigns a value, thus you are assigning num a value of 1 with this code
num = 1
Replace the single = with double ==.
num == 1
Here is a list of JavaScript comparison and logical operators.
Upvotes: 0
Reputation: 14649
=
is considered an assignment operator. You want the equality operator ==
, which is a comparison operator
function numberdescription() {
var num = Math.floor(Math.random() * 3 + 1)
if (num == 1) {
desc = "wealthy";
} else if (num == 2) {
desc = "middle wealth";
} else {
desc = "dirt poor";
}
document.getElementById("random").innerHTML = desc;
}
Upvotes: 2