How to get random array element onclick of a button in Javascript - javascript

I have a java script array with large number of elements inside it, on click of a button I want to display the any random array element on screen, for which I have used Math.random function, but not sure why it is not working.
here is my code below.
<html>
<head>
<title>Demo</title>
</head>
<body>
<button id="getquotes" value="Quotes" onclick="Loadquotes();">Quotes</button>
<p id="quoteshere" ></p>
<script>
var Loadquotes= function(){
var quotes = new Array('Stack1','Stack2','Stack16','Stack17','Stack13','Stack14','Stack15','Stack6','Stack7','Stack8','Stack9','Stack10');
var i;
for (i=0;i<quotes.length;i++){
var newquotes = quotes[Math.floor(Math.random() * quotes.length)];
document.getElementById('quoteshere').value=newquotes;
}
};
</script>
</body>
</html>

quoteshere is P Tag value function won't work use innerText or innerHTML instead please find below snippet
var Loadquotes= function(){
debugger;
var quotes = new Array('Stack1','Stack2','Stack16','Stack17','Stack13','Stack14','Stack15','Stack6','Stack7','Stack8','Stack9','Stack10');
var i;
for (i=0;i<quotes.length;i++){
var newquotes = quotes[Math.floor(Math.random() * quotes.length)];
document.getElementById('quoteshere').innerText = newquotes;
}
};
<button id="getquotes" value="Quotes" onclick="Loadquotes();">Quotes</button>
<p id="quoteshere" ></p>

you can try this
var quotes = Array('Stack1','Stack2','Stack16','Stack17','Stack13','Stack14','Stack15','Stack6','Stack7','Stack8','Stack9','Stack10');
var Loadquotes= function(){
var newquotes = quotes[Math.floor(Math.random() * quotes.length)];
document.getElementById('quoteshere').innerHTML=newquotes;
};
<button id="getquotes" value="Quotes" onclick="Loadquotes();">Quotes</button>
<p id="quoteshere" ></p>

Try This
<html>
<head>
<title>Demo</title>
</head>
<body>
<button id="getquotes" value="Quotes" onclick="Loadquotes()"> Quotes </button>
<p id="quoteshere" ></p>
<script>
function Loadquotes(){
var quotes = new Array('Stack1','Stack2','Stack16','Stack17','Stack13','Stack14','Stack15','Stack6','Stack7','Stack8','Stack9','Stack10');
var newquotes = Math.floor(Math.random() * quotes.length);
document.getElementById('quoteshere').innerHTML = quotes[newquotes];
}
</script>
</body>

Related

Is there a way to print content of a array into a textarea?

I got a script that picks a random word from an array. What I want this to do is to print one of these arrays into a textarea after the user clicks a button.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var myArray = [
"Test",
"Work",
"Life"
];
var randomItem = myArray[Math.floor(Math.random()*myArray.length)];
document.body.innerHTML = randomItem;
</script>
</body>
</html>
You could select your text area with some javascript methods such as document.getElementById, document.querySelector and set its value.
const myArray = ["Test", "Work", "Life"];
// const textArea = document.getElementById('my-textarea');
const textArea = document.querySelector('#my-textarea');
function updateTextArea() {
var randomItem = myArray[Math.floor(Math.random() * myArray.length)];
textArea.value = randomItem;
}
<textarea name="" id="my-textarea" cols="30" rows="10"></textarea>
</br>
<button onclick="updateTextArea()">Update Textarea</button>

How should properly put addeventListener

AddEventListener won't work when I clicked the button, the class name is exact on the html.
And how to properly set the time interval. I want the ball rolling and stop on the given time example 10s.
This is the html file and below is the js code
<!DOCTYPE html>
<html>
<link rel ='stylesheet' href ="style.css">
<script src = 'main.js'></script>
<body>
<div class = "wrapper_main" align ='center'>
<div > This is a lotto app design sample
<div class="ball-size">
<img src = "numbers/ball-0.png" class = "balls-0">
<img src = "numbers/ball-0.png" class = "balls-1">
<img src = "numbers/ball-0.png" class = "balls-2">
</div>
<div onclick="myFunction()" class ="buttons">
<button class = "btn-roll"> Roll </button>
</div>
</div>
</div>
</body>
</html>
js file ----
document.querySelector(".btn-roll").addEventListener("click", myFunction);
/*
var timesRun = 0;
var interval = setInterval(myFunction, 0);
timesRun += 1;
if(timesRun ===10) {
clearInterval(interval);
} */
function myFunction() {
var balls, balls1, balls2;
balls = Math.floor(Math.random() * 10);
balls1 = Math.floor(Math.random() * 10);
balls2 = Math.floor(Math.random() * 10);
var ballsDOM = document.querySelector(".balls-0");
var ballsDOM1 = document.querySelector(".balls-1");
var ballsDOM2 = document.querySelector(".balls-2");
ballsDOM.src = "numbers/ball-" + balls + ".png";
ballsDOM1.src = "numbers/ball-" + balls + ".png";
ballsDOM2.src = "numbers/ball-" + balls + ".png";
console.log("done");
}
It is important to do the event biding, after the DOM is created and the button exists in the page.
For example this won't work:
<body>
<script>
document.querySelector('.btn-roll').addEventListener('click', myFunction);
function myFunction(){
alert(1);
}
</script>
<button class="btn-roll">click on me</button>
</body>
Because we binded an event on a button that is not exists yet. but:
<body>
<button class="btn-roll">click on me</button>
<script>
document.querySelector('.btn-roll').addEventListener('click', myFunction);
function myFunction(){
alert(1);
}
</script>
</body>
Will work fine.
You can use libraries like jQuery to ensure the DOM is ready like this:
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
document.querySelector('.btn-roll').addEventListener('click', myFunction);
// or:
// $('.btn-roll').on('click',myFunction);
})
function myFunction(){
alert(1);
}
</script>
<button class="btn-roll">click on me</button>
</body>

toExponential() Method not working

toExponential() Method is not working my code.
chrome console is giving this error:
Uncaught TypeError: number.toExponential is not a function.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JS Code Academy</title>
</head>
<body>
<input type="number" id="myInput" value="2.326">
<button id="myButton">Click Me!</button>
<p id="demo1"></p>
<p id="demo2"></p>
<script type="text/javascript">
document.getElementById("myButton").onclick = function() {
var number = document.getElementById("myInput").value;
var str = number.toExponential(2);
document.getElementById("demo1").innerHTML = str;
document.getElementById("demo2").innerHTML = typeof str;
};
</script>
</body>
</html>
toExponential is a method defined on the number class. So make sure that you are calling it on a number and not a string:
var value = document.getElementById("myInput").value;
var number = parseFloat(value);
if (!isNaN(number)) {
// The string value entered in the textbox was successfully parsed to a number
// we can now calculate the exponential:
var str = number.toExponential(2);
}
If you have <input type="number" id="myNumber" /> , the entry must be just numbers so it will be easier for users to work with it. Darin's code is a good solution.

I want to print a random string on my current page

I'm new at javascript, but I want a random string. this string should be printed on my current page.
I already have:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript">
var strings = ['aaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', 'ccccccccccccccccccccccccccccccccccccccc'];
var randomIndex = Math.floor(Math.random() * strings.length);
var randomString = strings[randomIndex];
document.getElementById('randomString').innerHTML = randomString;
</script>
</head>
<body>
<div id="randomString"></div>
</body>
according to JSFiddle, this should work, but it doesn't. what should I change?
It does not work because your javascript is executed before the #randomString div exists. So, you need to either move your javascript after the #randomString div in the code, or use onLoad attribute of the to execute the function when the document is ready, which means that you would need to wrap your current code in a function.
You try to access the div with the id randomString before it exists in the DOM. Move the <script> to the bottom (somewhere after the div) and it'll work.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<div id="randomString"></div>
<script type="text/javascript">
var strings = ['aaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', 'ccccccccccccccccccccccccccccccccccccccc'];
var randomIndex = Math.floor(Math.random() * strings.length);
var randomString = strings[randomIndex];
document.getElementById('randomString').innerHTML = randomString;
</script>
</body>
</html>
btw, your code missed the </html>
You may try this :
window.onload=function(){
var strings = ['aaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', 'ccccccccccccccccccccccccccccccccccccccc'];
var randomIndex = Math.floor(Math.random() * strings.length);
var randomString = strings[randomIndex];
document.getElementById('randomString').innerHTML = randomString;
}

Javascript variable access in HTML

Say I have the following JavaScript in a HTML page
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
</script>
<body>
<a href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>
How do I get the value of the variable "splitText" outside the script tags.
Thanks!
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
window.onload = function() {
//when the document is finished loading, replace everything
//between the <a ...> </a> tags with the value of splitText
document.getElementById("myLink").innerHTML=splitText;
}
</script>
<body>
<a id="myLink" href = test.html></a>
</body>
</html>
Try this :
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
$("#target").text(splitText);
});
</script>
<body>
<a id="target" href = test.html></a>
</body>
</html>
<html>
<head>
<script>
function putText() {
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
document.getElementById("destination").innerHTML = "I need the value of " + splitText + " variable here";
}
</script>
</head>
<body onLoad = putText()>
<a id="destination" href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>
In raw javascript, you'll want to put an id on your anchor tag and do this:
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
function insertText(){
document.getElementById('someId').InnerHTML = splitText;}
</script>
<body onload="insertText()">
I need the value of "splitText" variable here
</body>
</html>
Here you go: http://codepen.io/anon/pen/cKflA
Although, I must say that what you are asking to do is not a good way to do it. A good way is this: http://codepen.io/anon/pen/jlkvJ
The info inside the <script> tag is then processed inside it to access other parts. If you want to change the text inside another paragraph, then first give the paragraph an id, then set a variable to it using getElementById([id]) to access it ([id] means the id you gave the paragraph).
Next, use the innerHTML built-in variable with whatever your variable was called and a '.' (dot) to show that it is based on the paragraph. You can set it to whatever you want, but be aware that to set a paragraph to a tag (<...>), then you have to still put it in speech marks.
Example:
<!DOCTYPE html>
<html>
<body>
<!--\|/id here-->
<p id="myText"></p>
<p id="myTextTag"></p>
<script>
<!--Here we retrieve the text and show what we want to write...
var text = document.getElementById("myText");
var tag = document.getElementById("myTextTag");
var toWrite = "Hello"
var toWriteTag = "<a href='https://stackoverflow.com'>Stack Overflow</a>"
<!--...and here we are actually affecting the text.-->
text.innerHTML = toWrite
tag.innerHTML = toWriteTag
</script>
<body>
<html>

Categories