I am having some issues figuring out how to make the innerHTML/GetElement line of code to work. I have tried all other commands such as document.write
and alert
, both seem to work fine. I don't know how to structure the document.get
to include the getRandomArrayElements
function. I am rather new to the Javascript side of web development and have been playing around with code on here. Im trying to have a array always give me 3 numbers of the list when pressing the button. Everything is working except the alert and my attempt to get it responded to the button press. Any help would be appreciated.
<input id="btnSearch" type="button" value="Search" onclick="getRandomArrayElements();" />
<p id="demo"></p>
<script>
function getRandomArrayElements(arr, count) {
var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
while (i-- > min) {
index = Math.floor((i + 1) * Math.random());
temp = shuffled[index];
shuffled[index] = shuffled[i];
shuffled[i] = temp;
}
return shuffled.slice(min);
}
Here is where im having issues, I just want the function to rely on the button press and not on the alert and no matter how many variations I do of removing alert and combining the code of the last two lines it comes out wrong.
var numbers = ['1','2','4','5','5','7','8','9','10'];
alert( getRandomArrayElements(numbers, 3) );
document.getElementById("demo").innerHTML=random;
</script>
What you are trying to set to innerHTML is not set. Try this snippet:
function getRandomArrayElements(count) { var arr = ['1','2','4','5','5','7','8','9','10']; var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index; while (i-- > min) { index = Math.floor((i + 1) * Math.random()); temp = shuffled[index]; shuffled[index] = shuffled[i]; shuffled[i] = temp; } document.getElementById("demo").innerHTML=shuffled.slice(min); }
<input id="btnSearch" type="button" value="Search" onclick="getRandomArrayElements(3);" /> <p id="demo"></p>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.