Generating a random number in JavaScript - javascript

All I'm trying to do is have the user click a button to generate a random number. It seems to work, but the number only displays for a second before disappearing.
Here is my code.
<!DOCTYPE html>
<head>
</head>
<body>
<h3>
This is a random number generator!
</h3>
<form onsubmit= "randomNumber()">
<input type="submit" value="Click me!">
</form>
<script>
function randomNumber() {
document.write(Math.floor(Math.random() * 10));
}
</script>
<p id="number">
</p>
</body>
</html>

You need
<form onsubmit="randomNumber(); return false;">
to prevent a new load of the page and
function randomNumber() {
document.getElementById('number').innerHTML = Math.floor(Math.random() * 10);
}
to set the value.

Nina's answer is good, but you don't really need a form for that. How about this instead of your form?
<button onclick="randomNumber()">Click me!</button>
Then the randomNumber function would go as Nina suggested:
function randomNumber() {
document.getElementById('number').innerText = Math.floor(Math.random() * 10);
}
Since there is no form, there's no need to prevent the form from actually being sent.
Incidentally, this would put the random number in the p with id "number", which I guess is what you wanted. However, if you want to leave a page which contains just the number, use document.write instead of document.getElementById..., as in your original snippet.

Related

Javascript - Calculate average of numbers

pretty new here and in programming overall so I would really appreciate some help.
Now, I want to create a site that has a button which calls a function when clicked. This function brings up a prompt box that allows the user to insert numbers only, infinitely or until he clicks cancel on the prompt box or presses space.
When the insertion of the numbers has stopped, the function calculates the average of all the numbers inserted and displays the result on an alert box. I have tried it and here's my code so far.
<html>
<head>
<script type="text/javascript">
function calc_avg() {
var avg; var sum;var total;var num=1;
while (num>0) {
var x = parseInt(prompt("Please enter a number","0"))
if (x=="") {
break;
} else {
sum += x;
total++;
avg=sum/total;
window.alert(avg);
}
}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="calc_avg()" value="Calculate Average">
</form>
</body>
</html>
Thanks in advance!

Validate two text fields together in html

I want to compare two text fields to make sure that the summation of two values should be equal to 100. I couldn't find any java script for this matter.
You din't explained your problem well, but I think this is what you want:
<input id="first" type="text">
<input id="second" type="text">
<button onClick="onClick()">Click me</button>
function onClick(){
var first = parseInt(document.getElementById("first").value);
var second = parseInt(document.getElementById("second").value);
var sum = first + second;
if (sum == 100)
{
...//Your code here...
}
}
Please tell me if this din't work for you.

Javascript Random Number Generator comes up with NaN

I am trying to make a random number generator using a form. When you press the button, and enter in the maximum number, it comes up with a dialog box reading NaN, when it is meant to come up with the random number.
I have some code that looks like this:
<html>
<head>
</head>
<body>
<form name="gen">
<h1>Random Number Generator</h1>
<b>Number:</b> 1 to
<input id="numgen" type="text"/>
<button name="generate" type="submit" onclick="gennum()">Generate!</button>
<script>
function gennum()
{
alert(Math.floor(Math.random() * num.value + 1));
}
var num = document.getElementById('numgen').value;
</script>
</form>
</body>
</html>
I am not very good with Javascript, but I know a bit. If anyone knows how to fix this, I would be happy.
num.value is a string. Use parseInt(num.value, 10) to turn it into a number, that way it can be added to a number appropriately.
Also, it looks like you're getting the value twice, and the first time is when the page loads (so it doesn't have a value yet:
var numElem = document.getElementById('numgen'); //remove value here
then in your function:
alert(Math.floor(Math.random() * parseInt(num.value + 1)));
and, you need to use type="button" on your button, or the page will reload.
Here's your code refactored with better practices.
Live demo here (click).
Markup:
<form name="gen">
<h1>Random Number Generator</h1>
<b>Number:</b> 1 to
<input id="numgen" type="text"/>
<button id="generate" type="button">Generate</button>
</form>
JavaScript:
/* get element references */
var genButton = document.getElementById('generate');
var numInput = document.getElementById('numgen');
//use javascript to add the click function
genButton.addEventListener('click', function() {
/* it's easier to read and debug if you break things up
* instead of putting it all on one line with tons of ((()))
*/
var rand = genRandom(1, parseInt(numInput.value, 10));
alert(rand);
});
function genRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

result of input box times 2 appears in window not div

I'm trying to get a text box where you can enter a number and then you click the button and it will multiply it by two and display that result in theDiv. Right now, it opens a new page for the result, and displays the entered number, not the number times two. What am I doing wrong? Beginner here, please be gentle! Thank you!!
<html>
<script>
function doubleit()
{
var theNumber=document.write(parseFloat(document.getElementById('theInput').value));
var doubleNumber =document.getElementById('theNumber')*2;
document.getElementById('theDiv').innerHTML(document.getElementById('doubleNumber'))
}
</script>
<body>
<p>Value: <input type="text" id="theInput" value="" size=10>
<input type="button" id="theButton" value="click me!" onclick="doubleit()"></p>
<div id="theDiv"></div>
</body>
</html>
It's the call to document.write that is replacing the page. Remove it:
var theNumber=parseFloat(document.getElementById('theInput').value);
When you want the value of a variable, you shouldn't use document.getElementById:
var doubleNumber = theNumber * 2;
innerHTML is a property, not a method:
document.getElementById('theDiv').innerHTML = doubleNumber;
var doubleNumber = Number(theNumber, 10)*2;
document.getElementById('theDiv').innerHTML(doubleNumber);
Something like this
function doubleit()
{
var theNumber=parseFloat(document.getElementById('theInput').value) * 2;
document.getElementById('theDiv').innerHTML = theNumber;
}
Try This Solution :
Use the id of your button to call the function to calculate result.
theButton.onclick = function doubleit()
{
//Simply get the number from user and parse it as float.
var theNumber=parseFloat(document.getElementById('theInput').value);
//Multiply it with 2
var doubleNumber =theNumber*2;
//Display the result in another div
document.getElementById('theDiv').innerHTML = doubleNumber;
}
Demo

Javascript html input element changes how to load into function?

I want user to load page, default value is 10 so it should calculate all variables for default value first, then I want user to enter his own value and click submit and the value gets updated.
Seems it needs onclick event that should call a function to recalculate the value.
I tried first without intparse and .value and no onclick event, then I figured out I need Intparse and .value to get integer. When setting default value on input id 1 it calculates three numbers correctly upon page load.
However when I put it in a function before it would calculate all three numbers correctly then page would reload for some reason and it goes back to default, This one doesn't work at all.
Can somebody explain what I did wrong?
<html>
<head>
</head>
<body>
<form id="frm1">
<input type="number" id="1" name="1" value="10"><br>
<input type="submit" onclick="myFunction()" id="s" value="Submit">
</form>
<p id="t"></p>
<script type="application/javascript">
Function myFunction() {
var N = parseInt(document.getElementById("1").value);
var m = N;
var cm = m * 100;
var mm = m * 1000;
document.getElementById("t").innerHTML = "" + m + " " + cm + " " + mm; }
</script>
</body>
</html>
Change the form to a div. This worked for me when I tried to run your code.

Categories