Shawn -
Shawn -

Reputation: 109

How random options in button?

 var options = [$("#option1"), $("#option2"), $("#option3"), $("#option4")]
            let randomOption = options.sort(() => .5 - Math.random());;
            console.log(randomOption[0])
            console.log(randomOption[1])
            console.log(randomOption[2])
            console.log(randomOption[3])
            $("#option1").text(randomOption[0].text())
            $("#option2").text(randomOption[1].text())
            $("#option3").text(randomOption[2].text())
            $("#option4").text(randomOption[3].text())
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script>
<button id="option1">1</button>
<button id="option2">2</button>
<button id="option3">3</button>
<button id="option4">4</button>

Why random doesn't work ?

cosole.log is correct, but in fact not real. I want to move random option in button.

But if I reload the page many times only $("#option1").text() is correct.

Upvotes: 0

Views: 30

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370639

You're assigning text to options while retrieving text from options that may have already had random text assigned.

Extract the text alone first:

const options = [$("#option1"), $("#option2"), $("#option3"), $("#option4")];
const texts = options
  .map(opt => opt[0].textContent)
  .sort(() => .5 - Math.random());
$("#option1").text(texts[0]);
$("#option2").text(texts[1]);
$("#option3").text(texts[2]);
$("#option4").text(texts[3]);
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<button id=option1>1</button>
<button id=option2>2</button>
<button id=option3>3</button>
<button id=option4>4</button>

Upvotes: 1

Related Questions