Javascript Random Number Generator comes up with NaN - javascript

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;
}

Related

Javascript random integer button

I am attempting to make a button that when clicked outputs an integer from 1-11. I have tested the "getRandomInt" function and it works, however when I try to add the button aspect nothing comes up when I click the button. Also the console does not log any errors.
code:
<form>
<input type="button" onclick="getRandomInt()" value="Click Here">
<br>
</form>
<script type="text/javascript">
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
};
document.write(getRandomInt(1, 12));
</script>
Can someone explain it in layman's terms how to fix this because the function should be correct, I think the button is wrong somehow and I think the two aren't being connected properly.
You need to supply arguments to getRandomInt when you call it. You also need to wrap the function call in something like document.write so you can see the output
<form>
<input type="button" onclick="document.write(getRandomInt(1, 10))" value="Click Here">
<br>
</form>
<script type="text/javascript">
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
};
document.write(getRandomInt(1, 12));
</script>
You are missing the glue between your program logic (getRandomInt()) and the presentation (document.write()), i. e. later statement is not part of your button's event handler.
I'd like to propose the following solution which avoids calling document.write and instead sets the text property of a dedicated <span id='display-random'>:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
var button = document.getElementById('button-random'),
display = document.getElementById('display-random');
button.addEventListener('click', function(event) {
display.textContent = getRandomInt(1, 12);
});
<form>
<input type="button" id="button-random" value="Click Here">
</form>
<span id="display-random"></span>

Generating a random number in 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.

Number Converter JQuery

I am a beginner and I have the following problem/code for the main body:
<body>
<form action="#">
<input type="text" id="start" />
=
<input type="text" id="finish" />
</form>
<script>
$(function() {
var cVal = $("#start").val();
var fVal = $("#finish").val();
});
</script>
</body>
With two text boxes, I would like the value entered in the celsius text box to be converted into fahrenheit in the other text box. I have tried to use the
keyup()
function but failed to produce the results I want.
typing 15 into the celsius box should result in 59 in fahrenheit. I understand that .val() does not take any arguments, so where would I do the computation for converting the numbers? And how can I incorporate keyup?
Any help is appreciated!
The val function does take arguments, you can pass it the new value and it will update textbox contents. Click the link on val, it will take you to the jQuery documentation, where all possible calls are explained. Or see the example below.
function fahrenheitToCelsius(fahrenheit) {
var val = 0;
// perform calculation
return val;
}
function celsiusToFarenheit(celsius) {
var val = 0;
// perform calculation
return val;
}
$(function() {
$("#start").on('keyup', function() {
$("#finish").val(celsiusToFarenheit($(this).val()));
});
$("#finish").on('keyup', function() {
$("#start").val(fahrenheitToCelsius($(this).val()));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
<input type="text" id="start" /> Celsius
=
<input type="text" id="finish" /> Fahrenheit
</form>
This is such a simple thing to do, jQuery is not needed at all, and because you haven't tagged jQuery here comes a plain javascript solution.
What you need to do is the add a keyup trigger on each of the input elements.
To grab our input fields we use document.getElementById(id), we use this because you've added the id attribute to your fields (it's faster than the latter method I'm mentioning). We could've used document.querySelector(selector) to get our input fields to. If you had used name="celsius" on the celsius field, we could've used document.querySelector('input[name="celsius"]') to grab that element.
What we need to do next is to an a keyup trigger to both our input fields. This is done with element.onkeyup = function() {}, in each of those functions we calculate the value for the other field.
var celsius = document.getElementById('start'),
fahrenheit = document.getElementById('finish');
celsius.onkeyup = function() {
fahrenheit.value = this.value * 9/5 + 32;
}
fahrenheit.onkeyup = function() {
celsius.value = (this.value - 32) * 5/9;
}
<form action="#">
<input type="text" id="start" /> Celsius
=
<input type="text" id="finish" /> Fahrenheit
</form>
The jQuery .val() function is an overload function which means it takes 0 up to 1 argument and it's effect varies on the number of arguments passed.
As you can see in my example calling celsiusInput.val() just returns the current value of the field. However if you use it like this farenheitOutput.val(farenheit) the current value of the input is overwritten by the variable passed.
const updateFarenheit = () => {
// find the input and output in the dom by their id
const celsiusInput = $("#start");
const farenheitOutput = $("#finish");
// get the input value
const celsius = celsiusInput.val();
const farenheit = celsius * 9 / 5 + 32;
// update the farenheit output
farenheitOutput.val(farenheit);
}
// this function runs when all js is loaded aka. "document ready"
$(document).ready(function() {
// get input field by id
const celsiusInput = $("#start");
// we pass the updateFarenheit function we defined before as the function which should run
// as soon as the keyup event occures on our celsiusInput field
celsiusInput.keyup(updateFarenheit);
});
<html lang="">
<head>
<meta charset="utf-8">
<title>Celsius to Farenheit</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form action="#">
<input type="text" id="start" /> =
<input type="text" id="finish" />
</form>
</body>
</html>

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