Suppose I have a html page: <h1 id="text"></h1> and js code: var text = ["text 1","text 2"] . How can I (at the press of a button) insert one (random) element from an array between tags?
- Have you tried to solve this issue yourself? - Drakonoved
- did not find a suitable solution - Anton Vasilenko
|
1 answer
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> var text = ["text 1", "text 2", "text 3", "text 4"] var text_label = $('#text'); var button = $('button'); button.click(function() { var random = getRandomInt(0, text.length); text_label.text(text[random]); }); function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1 id="text"></h1> <button>Magick!</button> Here is the complete code, and a brief explanation.
getRandomInt - returns a random integer from min to max.
When you click on the button, we transfer to getRandomInt 0 and the length of the array as parameters, we get a random value in this range, and paste the result into the text field
|