1

I'm trying to use HTML and JavaScript to create a simple program that will draw a random card from a deck that the user selects. The issue I'm running into is finding a way to use the option value from the HTML tag as a variable in the JavaScript function that draws the card. Here is my broken code.

<select id="hearts">
    <option value="hd12">-12</option>
    <option value="hd11">-11</option>
    <option value="hd0">-10</option>

<input type="button" onclick=drawFunction() value="Draw A Card">
<p id="draw"></p>
<script>;
var hd12 = ["AH"];
var hd11 = ["KH", "AH"];
var hd10 = ["QH", "KH", "AH"];

function drawFunction() {
    var deck = document.getElementById("hearts")
    var rand = deck[Math.floor(Math.random()*deck.length)];
    document.getElementById("draw").innerHTML = rand; 
}
;

I know if I replace "deck" with the name of the array variable the draw will work. So I'm just missing how to define "deck" using the selected option.

This is my first coding project so I'm sure I'm missing something simple. Thanks for your time and help.

Brandon
  • 13
  • 2
  • 1
    Store your `hd*` keys in an object, ie `var obj = {hd12: ['AH'], hd11: ['KH', 'AH'], ...}` then you can use `obj[deck.value]` – Phil May 11 '18 at 03:14

1 Answers1

0

You can access the value of an input element or select selected option, using the value attribute:

var value = document.getElementById("hearts").value;

To use the value as a variable, you have a few options:

Option 1

Access the variable thru the global scope (window object):

var hd12 = ["AH"];
var hd11 = ["KH", "AH"];
var hd10 = ["QH", "KH", "AH"];

var deck = window[document.getElementById("hearts").value];

Option 2

You could change how you setted your data, and convert it to an object, and then access the object by its key:

var definitions = {
  'hd12' : ["AH"],
  'hd11' : ["KH", "AH"],
  'hd10' : ["QH", "KH", "AH"]
};

var deck = definitions[document.getElementById("hearts").value];

Hope it helps!

muecas
  • 4,265
  • 1
  • 8
  • 18