Looking to add a random number to html element? [duplicate] - javascript

Need help with Javascript to generate number in HTML. I'm close but can't get it to quite work. Help would be appreciated.
http://jsfiddle.net/xmPgR/251/
function getNumber() {
var minNumber = 0; // The minimum number you want
var maxNumber = 100; // The maximum number you want
var randomnumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
$('#myNumber').html(randomnumber); // Sets content of <div> to number
return false; // Returns false just to tidy everything up
}
window.onload = getNumber; // Runs the function on click
document.getElementById("yourNumber").innerHTML = randomnumber;
<div id="myNumber"></div>
<p id="yourNumber">
</p>

Your onload works after the next statement, because it works asynchronously. And besides this, you use a randomnumber outside from it's scope, where it is not accessible.
So I suggest you to return the randomnumber from the function and use that function in the onload event handler. Inside that handler call your function, get the number and assign to your element's text.
And also if your getNumer's logic is to return the number, don't assign anything inside it, just return the number. It's responsibility is to return a random number. Pass the range to it, don't hard code: in another place you can need a random number in the different range. Other logic implement outside of that function.
function getRandomNumber(minRange, maxRange) {
return Math.floor(Math.random() * (maxRange + 1) + minRange);
}
window.onload = function() {
const rand = getRandomNumber(0, 100);
document.getElementById("yourNumber").innerHTML = rand;
$('#myNumber').html(rand);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myNumber"></div>
<p id="yourNumber"></p>

Here you go:
function getNumber() {
var minNumber = 0; // The minimum number you want
var maxNumber = 100; // The maximum number you want
var randomnumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
document.getElementById("myNumber").innerHTML = randomnumber; // Sets content of <div> to number
return false; // Returns false just to tidy everything up
}
window.onload = getNumber; // Runs the function on click
<div id="myNumber"></div>
<p id="yourNumber">
</p>

Related

How to use JavaScript Math.random() within HTML p tag

I am trying to print 1 random number within my <p> in HTML.
JavaScript:
function number()
{
var minNumber = 1; // The minimum number you want
var maxNumber = 5; // The maximum number you want
var randomNumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
document.getElementById("randomNum").innerHTML = randomNumber; // Sets content of <div> to number
return false; // Returns false just to tidy everything up
}
window.onload = number; // Runs the function on click
HTML:
<div class = card>
<div id="randomNum">
<h2>Header</h2>
<p>stats - [randomNumber] <br/> stat 2 - [randomNumber] </p>
</div>
</div>
(I could not get my HTML to post normally so I had to make it ugly. Sorry...)
My random number will print off to the side, and it is unable to print more within the same p. I was wondering if there is a way to place my random number from JavaScript within my p in HTML and keep all the css settings within the other div class card.
Thank you!
If I understand your question correctly, you want to place the random number in the p instead of the div, and have it append each time.
You should create an element each time with document.createElement and append it to the div, like this
function number()
{
var minNumber = 1; // The minimum number you want
var maxNumber = 5; // The maximum number you want
var randomNumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
var newNumber = document.createElement("p");
newNumber.innerText = randomNumber;
document.getElementById("randomNum").appendChild(newNumber);
return false; // Returns false just to tidy everything up
}
function number()
{
var minNumber = 1; // The minimum number you want
var maxNumber = 5; // The maximum number you want
var randomNumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
//document.getElementById("randomNum").innerHTML = randomNumber; // Sets content of <div> to number
var x = document.getElementsByClassName("randNum");
x[0].innerHTML = randomNumber;
x[1].innerHTML = randomNumber;
return false; // Returns false just to tidy everything up
}
window.onload = number; // Runs the function on click
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class = card>
<div id="randomNum">
<h2>Header</h2>
<p>stats - <span class="randNum"></span> <br/> stat 2 - <span class="randNum"></span> </p>
</div>
</div>
</body>
</html>
You have to give the P element a ID, then do a document.getElementbyID(whatever you put the ID for in the P tag) = randomNumber Your Html should be
<p id="whatever you want"></p>
Hopefully that helps.

How to make this HTML/Javascript random number generator output multiple results?

Thank you in advance for any help you can provide. I have a simple onload random number generator I am having issues with.
Basically I am trying to insert the generated number between some text. I am having no luck, but seems like I have tried everything. It always puts a line between the phrase.
My second issue is I can't figure out how to have more than one random number output. I am new to JavaScript so any explanation would be more than appreciated!
function getNumber() {
var minNumber = 10; // The minimum number you want
var maxNumber = 10; // The maximum number you want
var randomnumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber);
document.getElementById("myNumber").innerHTML = randomnumber;
// Sets content of <div> to number
return false;
}
window.onload = getNumber;
<div id="myNumber"> </div>
<p id="yourNumber"> </p>
I am (random number) years old.
My brother is (random number) years old.
My dog had (random number) puppies last year.
I'm using the output-element, since it is supposed to be used for results... And I use querySelectorAll to get all the output-elements.
document.addEventListener("DOMContentLoaded", function(event) {
function getNumber() {
output => output.value = getNumber();
var minNumber = 10; // The minimum number you want
var maxNumber = 20; // The maximum number you want
return Math.floor(Math.random() * (maxNumber + 1) + minNumber);
}
// Using querySelectorAll to get all output-elements, and then update the value of the output-element with a random number.
document.querySelectorAll('output').forEach(
output => output.value = getNumber()
);
});
<div>I am <output name="me"></output> years old.</div>
<div>My brother is <output name="brother"></output> years old. </div>
<div>My dog had <output name="dog"></output> puppies last year. </div>
I would break down the tasks into a function that generates the random number and another one that updates the DOM.
That way, you can re-use the number generator
Kind of like this (see demo)
// gets a random number
function getNumber() {
var minNumber = 10; // The minimum number you want
var maxNumber = 10; // The maximum number you want
var randomNumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber);
return randomNumber;
}
// updates one DOM element given its id
function updateDom(id) {
var aRandomNumber = getNumber();
// Sets content of <div> to number
document.getElementById(id).innerHTML = aRandomNumber;
}
// updates all DOM elements listed
function updateAll() {
updateDom('myNumber');
updateDom('yourNumber');
updateDom('theirNumber');
}
// when window ready, call function
window.onload = updateAll();
<div>I am <span id='myNumber'></span> years old.</div>
<div>My brother is <span id='yourNumber'></span> years old. </div>
<div>My dog had <span id='theirNumber'></span> puppies last year. </div>
<div> is by default displayed with CSS display: block, which puts it on its own line. You could either set your own custom CSS, but I recommend you use <span> instead, which by default uses display: inline.
What about this or do you need a number between 10 and 10? You can't have any number between 10 and 10 beside 10.
function getNumber() {
var minNumber = 10; // The minimum number you want
var maxNumber = 10; // The maximum number you want
var randomnumber = Math.floor(Math.random() * 100);
document.getElementById("myNumber").innerHTML = randomnumber;
// Sets content of <div> to number
return false;
}
window.onload = getNumber;
<div id="myNumber"> </div>
<p id="yourNumber"> </p>

Changing a specific thing in a varible

I have a equation like this stored in a varible
(50 * 1.07^1) its very simple. I want to know how I can change the power each time a function runs like so: 50*1.07^2, 50*1.07^3 and so forth. Any help?
Here is my code:
var mathForCost = 50 * 1.07 ^ 1;
function gainCoinsPS() {
if (coins >= costPS) {
coinsPS += 10;
coins -= costPS;
// Here is where I am changing the cost each time the function runs,
// so I need to make the power(^1) add 1 each time
costPS = document.getElementById("changePrice1").innerHTML = "Cost: " + costPS;
} else {;
alert("You dont have enough coins!");
};
}
Save the power to a variable, and you can update it when needed. It is preferred that you put the equation into a function and pass power to it, and return the solution.
var power = 1,
eq = function(p){
return 50*1.07^+p; // returns solution
};
for(var i=0; i<10; i++){
power = i;
console.log( eq(power) ); // solution
}
You can store your power in a variable and increment it each time your function is called.
var power = 1;
function calculate() {
console.log(50 * Math.pow(1.07, power));
power++;
}
calculate();
calculate();
calculate();
In Javascript you can't really store an equation in a variable, except maybe as a string (but that is fraught with issues of its own). Your function will be evaluated the moment you execute, and the value of the output will instead be stored in the variable.
To do what you want to do, you would be better having a function that runs the equation, and increments the power each time-- this works if the power is in a higher scope (or it can be accomplished with a closure)
var power = 1;
function getCost()
var cost = Math.pow(50*1.07, power);
power++;
return cost;
}
Each time this function runs, it returns the calculated cost and also increments the value of power, so it will be one higher the next time it runs.
Alternately, if you wanted to go the closure route, you could do something like this:
var getCost = (function () {
var power = 1;
return function () {
var cost = Math.pow(50*1.07, power);
console.log(power);
power++;
return cost;
}
})();
You can store a state to the function that runs the equation. This helps you avoid adding more state outside of the function. Let the function keep track of how many times it has been called.
function calc() {
if (!this.i) {
this.i = 1;
}
return (50 * Math.pow(1.07, this.i++));
}
console.log(calc());
console.log(calc());
console.log(calc());
There is Math.pow function is javascript for this.
You can use something like this
var pow = 1;
for(var power=1; power<limit; power++){ // run the loop upto a limit
console.log(Math.pow(50*1.07, power);
}
To increment power of 1.07 by 1, just multiply value by 1.07 every time (pow function is not needed at all)
var mathForCost = 50 * 1.07;
...
mathForCost = mathForCost * 1.07;
You could use a function for it.
getCost = function (n) { return 50 * Math.pow(1.07, n); };
Or with ES6's arrow function
getCost = n => 50 * Math.pow(1.07, n);
Call it with
value = getCost(1);

Using math.random in button to set a select option?

I'm trying to make a button that randomly sets a select option when clicked. I can't figure out what I am doing wrong though...
http://jsfiddle.net/GamerGorman20/nw8Ln6ha/25/
$('#rand').click(
function() {
randNum();
var num = "";
document.getElementById("mySelect").value.innerHTML = favWebComics[num];
});
var randNum = function() {
num = Math.round(Math.random() * 2) + 1;
return num;
};
The shown code is only a small part of the larger script housed in the linked jsfiddle.
I plan to add more selections later, but I want to get the code figured out before I spend time on those.
Worth mentioning, my understanding of this is very limited, so keeping the advice simple is GREATLY appreciated.
The relevant part of your code that you will need to change will look like this when complete (see the updated jsfiddle):
$('#rand').click(function() {
var $select = document.getElementById('mySelect'),
max = $select.getElementsByTagName('option').length - 1;
$select.selectedIndex = randNum(1, max);
myFunction();
});
var randNum = function(min, max) {
num = Math.floor(Math.random() * (max - min + 1)) + min;
return num;
};
var myFunction = function() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
document.getElementById("image").innerHTML = favWebComics[x][1];
document.getElementById("web").innerHTML = favWebComics[x][0];
document.getElementById("tags").innerHTML = "Tags: " + favWebComics[x][2];
};
I haven't changed the style or structure of your code, but just some of the basic properties.
The problem you have is with innerHTML. You cannot set innerHTML on an element's value.
Instead, what you can do is generate a random number and set the selectedIndex property of the select element to that random number.
Then, you'll call the function that displays the images and whatnot that you need.
You cannot change the select with innerHTML like this:
document.getElementById("mySelect").value.innerHTML = favWebComics[num];
You have to instead change the value, and apply the change like so
$("#mySelect").val("New text").change();
or
$("#mySelect").prop('selectedIndex', index).change();

Set variable random number of dots

I am trying to set a variable random number of dots. I can generate random numbers using Math.random(). I tried this without any luck:
function generate() {
Math.floor(Math.random() * 500)
}
var randomdots = generate();
What is the correct approach to set a variable random number of dots?
This method does nothing useful, it throws away the result before using it. Maybe you want:
function generate() {
var count = Math.floor(Math.random() * 500);
var result = '';
for (i = 0; i < count; ++i) {
result = result + '.';
}
return result;
}
document.write(generate());
Remember that functions in JavaScript must have a return if you want to get a value from them.
You can also use this
function generate() {
var index = Math.floor(Math.random() * 500);
return new Array(index).join(".");
}
var randomdots = generate();
You could have a JavaScript that writes bullets on page load. Do it like this:
var number = Math.ceil((Math.random() * 500)) + 1;
for (i=0;i<number;i++){
document.getElementById('output').innerHTML += '• ';
}
<p id="output"></p>
Let me know if you need additional help!
Although caslaner's answer seems to be the easiest way to achieve this, for educational purposes, here's a recursive function that does the same.
function generate(str,rm) {
if(rm === undefined) rm = Math.floor(Math.random() * 500);
return rm ? generate((str||'') + '.',rm-1) : str;
}
document.write(generate());

Categories

Resources