Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Ned Redmond
5,615 PointsUsing a dropdown in Javascript: why won't it work?
https://codepen.io/nred/pen/oyBGxN
I am trying to build a dice roller inspired by the Object Oriented Javascript "Dice Roller 2015" project.
However, I can't figure out how to get the dropdown value (to choose dice sides) to feed into the dice roll function.
No matter what I try, whenever I trigger the dice roll, I get a d4 roll. What is happening here?
Relevant bits:
HTML:
<select id="typeDie" onchange="getDieType()">
<option value="4">d4</option>
<option value="6">d6</option>
<option value="8">d8</option>
<option value="10">d10</option>
<option value="12">d12</option>
<option value="20">d20</option>
<option value="100">d100</option>
</select>
Javascript:
//gets sides from dropdown in ui
function getDieType() {
return parseInt(document.getElementById("typeDie").value);
}
//determines number of sides
function Dice(sides) {
this.sides = sides;
}
let dieRoll = new Dice(getDieType());
//generates roll based on number of sides
Dice.prototype.roll = function () {
return Math.floor(Math.random() * this.sides) + 1;
}
1 Answer
James Anwyl
Full Stack JavaScript Techdegree Graduate 49,960 PointsHi Ned,
When your app loads, a new object is created using the Dice constructor function. It gets stored in the variable dieRoll.
let dieRoll = new Dice(getDieType());
When you click the button, the value stored in dieRoll doesn't change. So the number of sides is always 4.
Try moving the dieRoll = new Dice(getDieType()) into your button.onclick function
button.onclick = function() {
let dieRoll = new Dice(getDieType());
let result = dieRoll.roll();
console.log("result:", result);
};
This way, each time the button is clicked, the Dice constructor gets called and a new object is created (using the value of #typeDie).
A more concise way:
button.onclick = function() {
var result = new Dice(getDieType()).roll();
console.log(result);
};
Hope this helps :)
Ned Redmond
5,615 PointsNed Redmond
5,615 PointsThank you! That works!