i would like that a javascript function (or html?) could take a random sentence from a datalist in the same file, then show it when i click on a button with an "onclick" event. I am looking for the easiest way to do that. Someone have a little example please?
(Just looking around, trying javascript for the first time)
Thanks for your help, wish you a good day
CodePudding user response:
let dataList =["sentence 1","sentence 2","sentence 3","sentence 4"]
let div = document.getElementById('asd')
document.getElementsByTagName("button")[0].addEventListener("click",myFunc)
function myFunc(){
let x = parseInt(Math.random()* dataList.length )
div.innerHTML = dataList[x]
}
<button>click me</button>
<div id='asd'></div>
CodePudding user response:
This is easy using the function parseInt()
and Math.random()*n
:
var yourDataList = ["Option 1", "Option 2", "Option 3"]; // Define datalist
var myBtn = document.getElementById("yourIdHere"); //Declare button, replace yourIdHere with your ID
var randomNum = 0; //Decclre random number
function getRandom() { //Declare your function
randomNum = parseInt(Math.random() * yourDataList.length); //Get random number between 0 and the length of your datalist
return yourDataList[randomNum]; //Return your value
}
myBtn.addEventListener("click", function() { //Bind a listener to the button
alert(getRandom()); //Do whatever you want to with the random value
});
<button id = "yourIdHere">Click me!!</button>