Home > Software engineering >  Selecting a value and assigning as a variable is not working
Selecting a value and assigning as a variable is not working

Time:01-02

For Hangman game, I have some topics. I have "selectedTopic.value".

const topicsEl = document.querySelector("#topics")

function randomTopic() {
  return topicsEl.value[Math.floor(Math.random() * topicsEl.value.length)].toUpperCase()
}
<div >
  <label for="topics">Choose a topic:</label>

  <select id="topics">
    <option value="cities">Cities</option>
    <option value="animals">Animals</option>
  </select>

When I assign selectedTopic.value to a Math.random(), the result is a letter. How can I use selectedTopic.value as a variable for Math.random()?

CodePudding user response:

You can access the <option> elements of an HTMLSelectElement in multiple ways:

const elSelect = document.querySelector("select");
console.log(elSelect.options[0]);
<select>
  <option>Value 1</option>
  <option>Value 2</option>
</select>

const elSelect = document.querySelector("select");
console.log(elSelect.item(0));
<select>
  <option>Value 1</option>
  <option>Value 2</option>
</select>

  • Via accessing an index on the select element itself. This is effectively the same as using the options property:

const elSelect = document.querySelector("select");
console.log(elSelect[0]);
<select>
  <option>Value 1</option>
  <option>Value 2</option>
</select>

Sidenote: Prefer using the options property over accessing an index directly for readability.

CodePudding user response:

It looks like you're trying to use selectedTopic.value as an array, but it is actually a string. The value property of the selectedTopic element is a string that represents the value of the selected option element in the select element.

To use the selectedTopic.value as a variable for Math.random, you can do the following:

  1. First, you need to define an array of strings using the new Array method. and then get all the values inside the topics array For example:
const topics = selectedTopic.options;
const TopicArray = new Array();
for(let i = 0; i < topics.length; i  )
{
    TopicArray[i] = selectedTopic.options[i].value;
}
  1. Then, you can use Math.random to select a random element from the array:
const randomTopic = TopicArray[Math.floor(Math.random() * topics.length)].toUpperCase();

You can then use the randomTopic variable in your hangman game.

Full Code

const selectedTopic = document.querySelector("#topics");

const topics = selectedTopic.options;
const TopicArray = new Array();

for (let i = 0; i < topics.length; i  ) {
  TopicArray[i] = selectedTopic.options[i].value;
}
const randomTopic = TopicArray[Math.floor(Math.random() * topics.length)].toUpperCase();

console.log(randomTopic);
// The result from randomTopic variable is either "ANIMALS" or "CITIES".

check the code and the results here https://codepen.io/abdullahatrash/pen/abjZmYG

  • Related