I am making a website that will generate a random number using JS. But it shows undefined for some reason. I DON'T want that to come. Here is my code.
var showRandomNumberDiv = document.getElementById("show-random-number");
var number1 = document.getElementById("number-1");
var number2 = document.getElementById("number-2");
var generate = document.getElementById("generate");
var newPara = document.createElement("p");
generate.addEventListener("click", function() {
numbers = [];
for (var i = 0; i > number1 && i < number2; i++) {
numbers.push(i);
}
newPara.innerHTML = numbers[Math.floor(Math.random() * numbers.length)];
showRandomNumberDiv.appendChild(newPara);
})
<h1>Hello, and welcome to Random generator!</h1>
<h2>Not only numbers, but letters too!</h2>
<p>If you want to enter a <span style="font-style:italic; font-weight: bold;">positive</span> number, see below.</p>
<!-- Generate a random number -->
<input type="text" placeholder="number 1" id="number-1">
<input type="text" placeholder="number 2" id="number-2">
<input type="button" value="Generate" id="generate">
<div id="show-random-number">
</div>
<script src="javascript.js"></script>
You did made a few mistakes in your code. Here's fixed version:
var showRandomNumberDiv = document.getElementById("show-random-number");
var number1 = document.getElementById("number-1");
var number2 = document.getElementById("number-2");
var generate = document.getElementById("generate");
var newPara = document.createElement("p");
showRandomNumberDiv.appendChild(newPara);
generate.addEventListener("click", function() {
var numbers = [];
for (var i = parseInt(number1.value); i < parseInt(number2.value); i++) {
numbers.push(i);
}
newPara.innerHTML = numbers[Math.floor(Math.random() * numbers.length)];
})
<h1>Hello, and welcome to Random generator!</h1>
<h2>Not only numbers, but letters too!</h2>
<p>If you want to enter a <span style="font-style:italic; font-weight: bold;">positive</span> number, see below.</p>
<!-- Generate a random number -->
<input type="text" placeholder="number 1" id="number-1">
<input type="text" placeholder="number 2" id="number-2">
<input type="button" value="Generate" id="generate">
<div id="show-random-number">
</div>
<script src="javascript.js"></script>
To get value from input you have to use input.value property. You can also use parseInt function to convert string value to number.
Also here's optimized version of the code.
var showRandomNumberDiv = document.getElementById("show-random-number");
var number1 = document.getElementById("number-1");
var number2 = document.getElementById("number-2");
var generate = document.getElementById("generate");
var newPara = document.createElement("p");
showRandomNumberDiv.appendChild(newPara);
generate.addEventListener("click", function() {
var min = parseInt(number1.value);
var max = parseInt(number2.value);
newPara.innerText = min + Math.round(Math.random() * (max - min));
})
<h1>Hello, and welcome to Random generator!</h1>
<h2>Not only numbers, but letters too!</h2>
<p>If you want to enter a <span style="font-style:italic; font-weight: bold;">positive</span> number, see below.</p>
<!-- Generate a random number -->
<input type="text" placeholder="number 1" id="number-1">
<input type="text" placeholder="number 2" id="number-2">
<input type="button" value="Generate" id="generate">
<div id="show-random-number">
</div>
<script src="javascript.js"></script>
You can multiply Math.random() with difference between maximum and minimum values and add the result to the minimum value to get a random number between minimum and maximum values.
Related
I'm trying to make a loan calculator by making two range slider interact with one another then show a the monthly payments in a label, these are the two requirements:
Only show 5 values on the "Month" range slider: 12,18,24,30,36 months (solved by Alexander Solonik)
Calculate an interest of 75%. (solved myself)
ok the code has evolved this way,:
<!--first range slider: money needed to borrow-->
<script language="JavaScript">
function showpay() {
var princ = document.calc.loan.value;
var term = document.calc.months.value;
var intr = (75 / 1200)*1.16; /*must include taxes, depending on your country, in my case is 16%*/
var auxterm = 0;
switch(term){
case '1': auxterm = 12; break;
case '2': auxterm = 18; break;
case '3': auxterm = 24; break;
case '4': auxterm = 30; break;
case '5': auxterm = 36; break;
}
document.calc.pay.value = Math.round((princ * 1000) * intr / (1 - (Math.pow(1/(1 + intr), auxterm))));
// payment = principle * monthly interest/(1 - (1/(1+MonthlyInterest)*Months))
}
</script>
<center>
<form name=calc method=POST>
<table width=60% border=0>
<h1>¿How much money do you need?</h1>
<p>Borrow from $2,000 to $80,000</p><br>
<div>
<input name="loan" type="range" min="2" max="80" value="2" class="slider" id="myRange" style="color: black;">
<p><br><strong>$ <span id="demo"></span>,000</strong></p>
</div>
<script>
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;
slider.oninput = function() { output.innerHTML = this.value; }
</script>
<h1>In how many months would you like to pay?</h1>
<p>from 12 to 36 months.</p><br>
<div>
<input name="months" type="range" min="1" max="5" value="0" class="slider" id="input" style="color: black;">
<strong><p><span id="result"></span> months</p></strong>
</div>
<script>
var result = document.getElementById('result'), input = document.getElementById('input')
var arr = [12,18,24,30,36]
input.oninput = function() { result.innerHTML = arr[this.value - 1] }
input.oninput()
</script>
<!--<tr>
<p>$ <span oninput="showpay()" value=Calculate></span></p>
</tr>-->
<tr>
Monthly Payment
<input type=text name=pay size=10>
</tr>
<input type=button onClick='showpay()' value=Calculate><!-- oninput="showpay()"-->
</table>
</form>
</center>
It is basicly complete, however the interest calculation is wrong, on the month slider it takes the values: 1,2,3,4,5 as that is the value of the slider, i need it to take the value of the arr = [12,18,24,30,36] instead, any idea how to do this?
ok this is now solved, may this be of help to some school projet or an actual loan calculator. :)
For only specific values o be selected in the range slider you can do something like this
var result = document.getElementById('result'),
input = document.getElementById('input')
var arr = [12,18,24,30,36]
input.oninput = function() {
result.innerHTML = arr[this.value - 1]
}
input.oninput()
<input type="range" min="1" max="5" id="input" value="0">
<div id="result">
</div>
You have a typo, its slider not lider.
Change on line 22 to
slider.oninput = function() { output.innerHTML = this.value; }
And the value is not visible because you applied CSS color value white in p tag. Also change that to
<p class="subtitulo" style="color: black;"><br><strong><span id="demo2"></span> months</strong></p>
I am trying to make a tip calculator and the total variable returns a string because typeof bill is a string, why is it so, even though the text input box type is number?
output("bill entered is 1000 and no of person is 1):- string
150
150
1000150
document.querySelector('#persons').addEventListener('change', (findresult));
document.querySelector('#bill').addEventListener('change', (findresult));
document.querySelector('#percent').addEventListener('change', (findresult));
function findresult() {
var persons = document.getElementById('persons').value;
var bill = document.getElementById('bill').value;
var percent = document.getElementById('percent').value;
// console.log(persons);
console.log(typeof bill);
// console.log(percent);
var tip = (bill * percent) / 100;
var tip_person = tip / persons;
var total = bill + tip;
console.log(tip);
console.log(tip_person);
console.log(total);
}
<div class="container">
<h1>Tip calcuator</h1><br>
<div class="inputs">
<input type="number" class="inputfield" id="persons" placeholder="No of Persons"><br><br>
<input type="number" class="inputfield" id="bill" placeholder="Bill"><br><br>
<input type="number" class="inputfield" id="percent" placeholder="Tip%">
</div>
<br>
<div class="result">
<br>
<p>Tip Per Person :</p>
<p>TOTAL :</p>
</div>
</div>
Surround the bill, percent declaration values with parseFloat to allow for decimals while converting the value String to a Number.
var bill = parseFloat(document.getElementById('bill').value);
var percent = parseFloat(document.getElementById('percent').value);
You may allow decimals in the Number Input by using the step attribute and set it to 0.01. This will affect the values created when using the up,down button on the Input.
<input type="number" class="inputfield" id="bill" placeholder="Bill" step="0.01" >
document.querySelector('#persons').addEventListener('change', (findresult));
document.querySelector('#bill').addEventListener('change', (findresult));
document.querySelector('#percent').addEventListener('change', (findresult));
function findresult() {
var persons = document.getElementById('persons').value;
// Use parseFloat to allow for decimals
var bill = parseFloat(document.getElementById('bill').value);
var percent = parseFloat(document.getElementById('percent').value);
// console.log(persons);
console.log(typeof bill);
// console.log(percent);
var tip = (bill * percent) / 100;
var tip_person = tip / persons;
var total = bill + tip;
console.log(tip);
console.log(tip_person);
console.log(total);
}
<div class="container">
<h1>Tip calcuator</h1><br>
<div class="inputs">
<input type="number" class="inputfield" id="persons" placeholder="No of Persons"><br><br>
<!-- Allow cents to be allowed via the `step` attribute -->
<input type="number" class="inputfield" id="bill" placeholder="Bill" step="0.01" ><br><br>
<input type="number" class="inputfield" id="percent" placeholder="Tip%">
</div>
<br>
<div class="result">
<br>
<p>Tip Per Person :</p>
<p>TOTAL :</p>
</div>
</div>
User parseInt(), it will convert string into number.
function findresult() {
var persons = parseInt(document.getElementById('persons').value);
var bill = parseInt(document.getElementById('bill').value);
var percent = parseInt(document.getElementById('percent').value);
// console.log(persons);
console.log(bill);
// console.log(percent);
var tip = (bill * percent) / 100;
var tip_person = tip / persons;
var total = bill + tip;
console.log(tip);
console.log(tip_person);
console.log(total);
}
As mentioned by #Heretic Monkey, the input element has a property valueAsNumber and since the input type is always a number, we wouldn't have to worry about the parsing.
so we can use document.getElementById('persons').valueAsNumber
Also a few suggestions, it's always nice to break your code in smaller parts. Therefore separating the logic of fetching the input values and performing calculations separately will be a better approach and its not a good practice to call the DOM objects repeatedly.
For example, we can create a function for change event listener and read the event argument and update the necessary object of values,
document.querySelector('#persons').addEventListener('change', (update));
document.querySelector('#bill').addEventListener('change', (update));
document.querySelector('#percent').addEventListener('change', (update));
let values = {
persons: 0,
bill: 0,
percent: 0,
}
function update(event) {
values[event.currentTarget.id] = event.target.valueAsNumber;
findresult();
}
Finally, you can read the values as follows,
var persons = values["persons"];
var bill = values["bill"];
var percent = values["percent"];
So putting all together,
document.querySelector('#persons').addEventListener('change', (update));
document.querySelector('#bill').addEventListener('change', (update));
document.querySelector('#percent').addEventListener('change', (update));
let values = {
persons: 0,
bill: 0,
percent: 0,
}
function update(event) {
values[event.currentTarget.id] = event.target.valueAsNumber;
findresult();
}
function findresult() {
var persons = values["persons"];
var bill = values["bill"];
var percent = values["percent"];
var tip = (bill * percent) / 100;
var tip_person = tip / persons;
var total = bill + tip;
console.log(tip);
console.log(tip_person);
console.log(total);
}
<div class="container">
<h1>Tip calcuator</h1><br>
<div class="inputs">
<input type="number" class="inputfield" id="persons" placeholder="No of Persons" step="0.01"><br><br>
<input type="number" class="inputfield" id="bill" placeholder="Bill"><br><br>
<input type="number" class="inputfield" id="percent" placeholder="Tip%">
</div>
<br>
<div class="result">
<br>
<p>Tip Per Person :</p>
<p>TOTAL :</p>
</div>
</div>
Hope it helps.
I want to get a number from a form-control type = "number", compare it, and then if OK with the condition, perform multiplication, and division on it. After that I want to display the result as the contents of a <p> tag. How to accomplish this?
Here is what I have tried so far:
let amount = document.getElementById(".amount");
let marginAmount = document.getElementById(".marginAmount")
let submit = document.getElementById(".submit");
submit.addEventListener('click', calcAmount);
const calcLevel1 = amount * 7 / 100;
function calcAmount() {
let userAmount = Number(amount.value);
let level1 = 351;
if (userAmount <= level1) {
marginAmount.textContent = calcLevel1.value;
}
}
<div class="form">
<label for="points amount">Entrez un montant en points</label>
<input type="number" class="amount-enter" id="amount">
<input type="submit" value="Montant marge additionnelle" id="submit" class="submit-enter">
</div>
<p id="marginAmount" class="enter-margin"></p>
Here is the code corrected, there are. Which are to be deleted
I also added math.round to get rounded result:
<html>
<head>
<script>
function calcAmount() {
let userAmount = document.getElementById("amount").value;
let level1 = 351;
if (userAmount <= level1) {
document.getElementById("marginAmount").textContent = Math.round(userAmount * 7) / 100;
} else {
document.getElementById("marginAmount").textContent = "Amount is > 351";
}
}
</script>
</head>
<body>
<div class="form">
<label for="points amount">Entrez un montant en points</label>
<input type="number" class="amount-enter" id="amount">
<input type="submit" value="Montant marge additionnelle" id="submit" class="submit-enter" onclick="calcAmount()">
</div>
<p id="marginAmount" class="enter-margin"></p>
</body>
Three things:
You had . in your ID selectors, these shouldn't be there (they should be # but only in a querySelector method).
You were calculating calcLevel1 straightaway, which meant it was 0 * 7 / 100 which is 0.
You needed to calculate calcLevel1 with amount.value, which means you can remove calcLevel1.value when you're setting the textContent of the paragraph.
I also added an else statement so the textContent is emptied when the statement is false.
let amount = document.getElementById("amount");
let marginAmount = document.getElementById("marginAmount")
let submit = document.getElementById("submit");
submit.addEventListener('click', calcAmount);
function calcAmount() {
const calcLevel1 = amount.value * 7 / 100;
let userAmount = Number(amount.value);
let level1 = 351;
if (userAmount <= level1) {
marginAmount.textContent = calcLevel1;
} else {
marginAmount.textConten = "";
}
}
<div class="form">
<label for="points amount">Entrez un montant en points</label>
<input type="number" class="amount-enter" id="amount">
<input type="submit" value="Montant marge additionnelle" id="submit" class="submit-enter">
</div>
<p id="marginAmount" class="enter-margin"></p>
This might sound like a simple thing for you programmers out there but i can't seem to figure it out. I'm making a program that where among 4 numbers the largest is outputted. I've got the core code working but i can't seem to think how i can display the results on the screen. I would like it so that when the user types a number into a text box the result appears in another text box at the press of a button. Thanks for your time & help.
HTML
<html>
<head>
<meta charset="UTF-8">
<script src="Main.js" type="text/javascript"></script>
<link href="Main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<form id="Awesome">
<label>Input Numbers Here: </label><input type="text"
id="txtBox">
<br><br>
<label>Dec to Roman #: </label><input type="text" id="Results">
<br><br>
<input type="button" value="Calculate" id="Execute"
onclick="largestOfFour()">
</form>
</body>
</html>
Javascript
function largestOfFour(arr) {
var largestNumbers = [];
var currentLargest;
for (var x =0; x <arr.length; x++) {
currentLargest = 0;
for (var y = 0; y < arr [x].length; y++) {
if (arr[x][y] > currentLargest) {
currentLargest = arr[x][y];
}
}
largestNumbers.push(currentLargest);
}
return largestNumbers;
document.getElementById('Results').value = largestNumbers;
}
After entering the numbers in an input box, we can read its value as a string. Splitting that string with a space give us the numbers array. We will compare each number in that array to each other and save the biggest number in largest. Then we display its value in a Result box.
function largestOfFour() {
// get string from the input
var s = document.getElementById('txtBox').value;
var numbers = s.split(' ');
var largest = 0;
for (var x = 0; x < numbers.length; x++) {
var current = parseInt(numbers[x])
if (current > largest)
largest = current;
}
// display the largest number
document.getElementById('Results').value = largest;
}
<form id="Awesome">
<label>Input 4 Numbers (space separated): </label>
<input type="text" id="txtBox">
<br><br>
<label>Max #: </label>
<input type="text" id="Results" readonly>
<br><br>
<input type="button" value="Calculate" id="Execute" onclick="largestOfFour()">
</form>
I am trying to make an annual salary calculator using Javascript. Here is what I have so far:
<div id="fulldiv">
<p> Enter the following information to calculate your annual salary.</p>
<p>Hourly Wage:
<input type="text" name="wage" id="txt_wage" value ="0.00"/></p>
<p>Hours Per Week:
<input type="text" name="hours" id="txt_hours" value= "0.0"/> <br/><br/>
<button value="calculate" onclick="calcSalary()">Calculate</button></p>
<p id="results"></p>
<script type="text/javascript">
function calcSalary() {
var wage_element = document.getElementById('txt_wage');
var wage = parseInt(wage_element.value);
var hours_element = document.getElementById('txt_hours');
var hours = parseInt(hours_element.value);
var calculate = wage_element * hours_element * 52;
document.getElementByID('results').innerHTML = calculate;
}
</script>
</div>
When I click the button, nothing happens. Any thoughts?
Some typos in there. I have slightly rewritten and simplified the code to ensure the a) your calculations are on the value of the inputs and b) you are using labels to provide the text relative to the inputs - not p's.
function calcSalary() {
var wage = parseFloat(document.getElementById('txt_wage').value);
var hours = parseFloat(document.getElementById('txt_hours').value);
var calculate = wage * hours * 52;
document.getElementById('results').innerHTML = calculate;
}
<div id="fulldiv">
<p> Enter the following information to calculate your annual salary.</p>
<label for="txt_wage">Hourly Wage:</label>
<input type="text" name="wage" id="txt_wage" value ="0.00"/>
<label for="txt_hours">Hours Per Week:</label>
<input type="text" name="hours" id="txt_hours" value= "0.0"/>
<br/><br/>
<button value="calculate" onclick="calcSalary()">Calculate</button>
<p id="results"></p>
</div>
You code needs to be adjusted
var calculate = wage_element * hours_element * 52;
Should be changed into
var calculate = wage * hours * 52;
The problem is that you're calculating the element instead of the values.
#Gerard beat me to it by a minute, but here's the working code.
<div id="fulldiv">
<p> Enter the following information to calculate your annual salary.</p>
<p>Hourly Wage:
<input type="text" name="wage" id="txt_wage" value ="0.00"/></p>
<p>Hours Per Week:
<input type="text" name="hours" id="txt_hours" value= "0.0"/> <br/><br/>
<button value="calculate" onclick="calcSalary()">Calculate</button></p>
<p id="results"></p>
<script type="text/javascript">
function calcSalary() {
var wage_element = document.getElementById('txt_wage');
var wage = parseInt(wage_element.value);
var hours_element = document.getElementById('txt_hours');
var hours = parseInt(hours_element.value);
var calculate = wage * hours * 52;
document.getElementById('results').innerHTML = calculate;
}
</script>
</div>