I have a text field that I need to divide by certain inputs. I've tried using the code below but I am running in to issues. It does not take the decimal point in to account, and will return 0 if you use a decimal.
<input id="number" type="text"> ÷ 3.181818<br />
Your output is: <div id="output"></div>
<script type="text/javascript">
//obtain reference to number html element
var number = document.getElementById('number');
//obtain reference to output html element
var output = document.getElementById('output');
//what you want to divide to
var division = '3.181818'; // can't be 0, or the world will explode
//add an eventlistener to the change event on the number element
number.addEventListener('keyup', function(e) {
//get the value from the input
var val = parseFloat(number.value);
//check if it is a nan
if(!isNaN(val)) {
//round it to 0 digits
output.innerHTML = (val / division).toFixed(0) + "";
} else {
output.innerHTML = 'that\'s not a number!';
}
});
</script>
So for example if someone inputs their sensitivity in the text box as 1.2, it would then do 1.2 / 3.181818 = 0.37714287869
0.37714287869 being their new sensitivity.
Remove the toFixed and set div as a float 3.181818:
//obtain reference to number html element
var number = document.getElementById('number');
//obtain reference to output html element
var output = document.getElementById('output');
//what you want to divide to
var division = 3.181818; // can't be 0, or the world will explode
//add an eventlistener to the change event on the number element
number.addEventListener('keyup', function(e) {
//get the value from the input
var val = parseFloat(number.value);
//check if it is a nan
if (!isNaN(val)) {
output.innerHTML = val / division;
} else {
output.innerHTML = 'that\'s not a number!';
}
});
<input id="number" type="text"> ÷ 3.181818<br /> Your output is:
<div id="output"></div>
Related
What I want is, after the user enters the number of subjects, the system will show the number of input box according to the number of subjects entered, then when the user clicks on the button, it should show the sum. I tried many ways, but I failed to show the sum, anyone knows what is the mistake I made?
Below is my code:
function select() {
var x = parseInt(document.getElementById('1').value);
if (document.getElementById('1').value == "") {
alert("Please fill up number of subject");
} else if (isNaN(x) == true) {
alert("Please fill up number of subject with number");
} else {
var subject = parseInt(document.getElementById('1').value);
var sum = 0;
for (var num = 1; num <= subject; num++) {
document.write("Enter the mark for subject " + num + " : ");
var value = parseFloat(document.write("<input/><br>"));
sum += value;
}
var calc = document.write("<button>Next</button><br>");
calc.onclick = function() {
next()
};
function next() {
document.write("Total marks: " + sum + "%");
}
}
}
<html>
<body>
Enter the number of subject: <input type="text" onkeypress="return/[0-9]/i.test(event.key)" id="1" value=""><br>
<button onclick="select()">Check</button><br>
</body>
</html>
That's how I have rewritten a big part of your code. I have place inline comments to explain what I do.
function select() {
var x = parseInt(document.getElementById('1').value, 10);
// Getting the div that wraps the initial form.
var formWrapper = document.querySelector('.formWrapper');
// Getting the div, that is going to display the new fields and the results.
var results = document.querySelector('.results');
// I have switch your statement from x == '' to '' === x as it
// consists a good practice
if ( '' === x ) {
alert("Please fill up number of subject");
// I have remove the isNaN(x) == true, because the isNan will
// be either true or false.
} else if ( isNaN(x) ) {
alert("Please fill up number of subject with number");
} else {
// Using parseInt(x, 10) to set the base.
var subject = parseInt(x, 10);
// In this array, I store the auto-generated fields.
var fieldsList = [];
// Removing the first div from the DOM
formWrapper.parentElement.removeChild(formWrapper);
for ( var num = 1; num <= subject; num++ ) {
// I am creating a new field
var newField = document.createElement('input');
// I push the field into the array I made for the fields.
fieldsList.push(newField);
// I append the field in the HTML
results.appendChild(newField);
// I create a <br> tag
var br = document.createElement('br');
// And I append the tag in the DOM
results.appendChild(br);
}
// I create the button that is going to handle the Next functionality
var nextButton = document.createElement('button');
// I set the button text
nextButton.innerText = 'Next';
// I add an Event Listener for the click event.
nextButton.addEventListener(
'click',
function() {
// I reset the sum to 0
var sum = 0;
// I itterate the fields auto-generated and saved in the array
fieldsList.forEach(
function(field) {
// I get the value
sum += parseInt(field.value, 10);
}
);
// I create the field that is going to display the output
let resultText = document.createElement('div');
// I set the text based on the sum
resultText.innerText = "Total marks: " + sum + "%";
// I append the text message to the DOM
results.appendChild(resultText);
}
);
// I append the button to the DOM
results.appendChild(nextButton);
}
}
<html>
<body>
<div class="formWrapper">
Enter the number of subject: <input type="text" onkeypress="return/[0-9]/i.test(event.key)" id="1" value=""><br>
<button onclick="select()">Check</button><br>
</div>
<div class="results"></div>
</body>
</html>
I'm making a tip calculator and I would like the tip amount to display for the user to see. The problem I'm having is the output showing up as 'NaN' or 'undefined'. I've tried making changes to my code but I keep getting the same result.
function calculateTip() {
var billInput = document.getElementById('bill');
var tipPercentage = document.getElementById('tip');
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (bill * tipPercentageCalc).toFixed(2);
tipAmount = tipAmount.toString();
document.getElementById('display_text').innerHTML = 'Tip = $', +tipAmount;
};
<div id='calculate'>
<p>Bill: $<input id="bill" type="number" name="bill" placeholder="Enter bill amount" onchange="calculateTip()"></p>
<p>Tip: %<input id="tip" type="number" name="tip" placeholder="15%" onchange="calculateTip()"></p>
<input type="button" name="submit" onclick="calculateTip();">
</div>
<div id="display">
<h4 id="display_text"></h4>
</div>
You forgot to get the value of your fields. Because without the property .value, it returns HTMLObject.
function calculateTip() {
var billInput = parseFloat(document.getElementById('bill').value);
var tipPercentage = parseFloat(document.getElementById('tip').value);
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (bill * tipPercentageCalc).toFixed(2);
tipAmount = tipAmount.toString();
document.getElementById('display_text').innerHTML = 'Tip = $', + tipAmount;
};
You are reading billInput and tipPercentage as HTML element objects instead of the text the user types into them, which will be their .value properties.
function calculateTip() {
// get the VALUE property of the textbox elements
// parseInt will turn them into numbers if they're not already.
// if they are not numbers you cannot use them in math.
var billInput = parseInt(document.getElementById('bill').value);
var tipPercentage = parseInt(document.getElementById('tip').value);
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (billInput * tipPercentageCalc);
// isNaN stands for "is Not a Number"
// this checks if tipAmount is not a number
// if it is not we simply set it to the number 0
if (isNaN(tipAmount)) {
tipAmount = 0;
}
// when you concatenate a number to a string you do not need to turn it into a string.
// it will automatically be converted
document.getElementById('display_text').innerHTML = 'Tip = $' + tipAmount;
};
function calculateTip() {
// get the VALUE property of the textbox elements
// parseInt will turn them into numbers if they're not already.
// if they are not numbers you cannot use them in math.
var billInput = parseInt(document.getElementById('bill').value);
var tipPercentage = parseInt(document.getElementById('tip').value);
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (billInput * tipPercentageCalc);
// isNaN stands for "is Not a Number"
// this checks if tipAmount is not a number
// if it is not we simply set it to the number 0
if (isNaN(tipAmount)) {
tipAmount = 0;
}
// when you concatenate a number to a string you do not need to turn it into a string.
// it will automatically be converted
document.getElementById('display_text').innerHTML = 'Tip = $' + tipAmount;
};
<div id='calculate'>
<p>Bill: $<input id="bill" type="number" name="bill" placeholder="Enter bill amount" onchange="calculateTip()"></p>
<p>Tip: %<input id="tip" type="number" name="tip" placeholder="15%" onchange="calculateTip()"></p>
<input type="button" name="submit" onclick="calculateTip();">
</div>
<div id="display">
<h4 id="display_text"></h4>
</div>
You're loading the element instead of the element value when declaring the variables billInput and tipPercentage. Try with this code:
var billInput = document.getElementById('bill').value;
var tipPercentage = document.getElementById('tip').value;
so If I entered 10, number 10 should be printed ten times
function function_name(number) {
for (var counter = 1; counter <= number; counter++) {
document.write("the number is" + number);
}
}
<label for="number">Enter number: </label>
<input name="number" id="number" />
Looks like you just need to:
Add a button to your HTML
Add a click handler to your button that will activate your function
function writeTimes(number) {
for (var counter = 1; counter <= number; counter++) {
document.write("the number is" + number);
}
}
function doTheThing() {
var input = document.getElementById("my-input"); //get the input element
var numberOfTimes = input.value; //get the number of times
writeTimes( numberOfTimes ); //call your function
}
<label for="number">Enter number: </label>
<input id="my-input" name="number" id="number" />
<button onclick="doTheThing()">Go</button>
// This function *does* something. Give it a name that reflects it's behavior.
// You can always rename it later if you change what it does.
//
function spamNumber(number) {
// Use let instead of var, it's replacement for var with less wtf behavior
//
for (let counter = 1; counter <= number; counter++) {
// I don't care for document.write. It's totally unusable in production code.
// But sure, why not? At least add a line break so the outputs
// don't smush together.
//
document.write("the number is " + number + '<br/>');
}
}
// Find the input element so we can add a listener
//
document.querySelector('input')
// Listening in this case only to keydowns that occur while input has focus.
//
.addEventListener('keydown', function onKeydown(evt) {
if (event.key === 'Enter') {
// evt.target is the input element, number in it's value property.
// Force value to integer in case someone inputs garbage. We can
// fail silently and move on.
//
spamNumber( parseInt(evt.target.value) || 0)
}
})
// Now type in your number and press Enter
<label for="number">Enter number: </label>
<input name="number" id="number" />
From your question and comments , i think you are looking for this:
onload = function (){
var result = document.getElementById('result');
var number = document.getElementById('number');
number.oninput = function (){
if(number.value == "0" || number.value.length == ""){result.innerHTML="";}else{}
var counter = "";
var repeat =number.value;
while (repeat > 0) {
repeat--;
var str =" (the number is " + parseInt(number.value)+" )";
result.innerHTML= str.repeat(number.value);
}
return counter;
number.onpropertychange = number.oninput;
number.onchange = number.oninput;
}};
<label for="number">Enter number: </label>
<input name="number" id="number" /><br />
<span id=result></span>
I am trying to build a javascript calculator as per freecodecamp requirement on front end track.
Codepen link: https://codepen.io/ekilja01/pen/MoXROe
By pressing any number on calculator the display must be changed to that number. Also the var number has to remember its value, because by clicking the number again it becomes a new number, so after that I can use operators and parseInt to evaluate and display the final value. I've got an idea how can this be implemented by using jQuery, so something like this:
$("#numbers a").not("#clear,#clearall").click(function(){
number += $(this).text();
totaldiv.text(number);
});
$("#operators a").not("#equals").click(function(){
operator = $(this).text();
newnumber = number;
number = "";
totaldiv.text("0");
});
$("#clear,#clearall").click(function(){
number = "";
totaldiv.text("0");
if ($(this).attr("id") === "clearall") {
newnumber = "";
}
});
//Add your last .click() here!
$("#equals").click(function(){
if (operator === "+"){
number = (parseInt(number, 10) + parseInt(newnumber,10)).toString(10);
} else if (operator === "-"){
number = (parseInt(newnumber, 10) - parseInt(number,10)).toString(10);
} else if (operator === "÷"){
number = (parseInt(newnumber, 10) / parseInt(number,10)).toString(10);
} else if (operator === "×"){
number = (parseInt(newnumber, 10) * parseInt(number,10)).toString(10);
}
totaldiv.text(number);
number = "";
newnumber = "";
});
But what can be equivalent to this in vanilla js? I've tried .textContent or .innerHTML, but neither of them work. On calculator's dispay either undefined or <a>1</a> ... <a>AC</a>. Also what is the equivalent to .not(). Any help will be much appreciated.
html:
<div id="calculator">
<p id="cal">CALCULATOR</p>
<div id="total">
</div>
<div id="operators">
<a>÷</a>
<a>×</a>
<a>+</a>
<a>-</a>
<a>=</a>
</div>
<div id="numbers">
<a>1</a>
<a>2</a>
<a>3</a>
<a>4</a>
<a>5</a>
<a>6</a>
<a>7</a>
<a>8</a>
<a>9</a>
<a id="clear">C</a>
<a>0</a>
<a id="clearall">AC</a>
</div>
</div>
js:
document.addEventListener('DOMContentLoaded', function (event) {
console.log('DOM OK');
// Declare variables for number, new number and operators
var number, newNumber, operator = "";
// Declare variable total number to display total on the calculator's display
var totalNumber = document.getElementById("total");
totalNumber.textContent = "0";
document.getElementById("numbers").addEventListener('click', function(){
number += this.textContent;
totalNumber.textContent = number;
})
})
You may want to use the event argument in the callback function. For example:
number = "";
document.getElementById("numbers").addEventListener('click', function(e){
number += e.target.textContent;
totalNumber.textContent = number;
})
More information on the event target properties specifically:
https://developer.mozilla.org/en-US/docs/Web/API/Event/target
Entire JS code:
document.addEventListener('DOMContentLoaded', function (event) {
console.log('DOM OK');
// Declare variables for number, new number and operators
var number, newNumber, operator = "";
// Declare variable total number to display total on the calculator's display
var totalNumber = document.getElementById("total");
totalNumber.textContent = "0";
number = "";
document.getElementById("numbers").addEventListener('click', function(e){
number += e.target.textContent;
totalNumber.textContent = number;
})
})
just to display which number is clicked on-
var totalNumber = document.getElementById("total");
totalNumber.textContent = "";
document.getElementById("numbers").addEventListener('click', function(e){
totalNumber.textContent += e.target.innerText;
})
So I've written a web page with a few JavaScript functions.
The page runs perfectly in Dreamweaver but when I tried it out in a browser (Google Chrome and Firefox) the JavaScript flashes for a split second then clears. I have no idea at all why this is.
<body>
<form name="myForm">
<ol>
<li>
<h1> TILE CALCULATOR</h1>
</li>
<li>
<label for="wall height">Wall height (cm)</label>
<input type="text" id="wall_height" />
</li>
<li>
<label for="wall width">Wall Width (cm)</label>
<input type="text" id="wall_width" />
</li>
<li>
<label for="tile height">Tile Height (cm)</label>
<input type="text" id="tile_height" />
</li>
<li>
<label for="tile width">Tile Width (cm)</label>
<input type="text" id="tile_width" />
</li>
<button onclick="javascript:validate();"> Calculate </button>
</ol>
</form>
<br />
<p id="result"></p>
<br />
<canvas id="myCanvas">
Your browser does not support this feature</canvas>
<br />
<br />
<script language="javascript" type="text/javascript">
//functoin to validate the inputs by the user
//user can only enter a number and all fields must be filled
function validate()
{
//first make sure canvas is clear
clearCanvas()
//take the inputs as variables
var x = document.getElementById("tile_width").value;
var y = document.getElementById("tile_height").value;
var z = document.getElementById("wall_width").value;
var i = document.getElementById("wall_height").value;
//check if the user has entered nothing and alert if they have
if (x==null || x=="" || y==null || y=="" || z==null || z=="" || i==null || i=="")
{
alert("All the fields have to be filled out!");
clearResult();
}
// check if the user has entered invalid values, only numbers can be entered
if (isNaN(x) == true || isNaN(y) == true || isNaN(z) == true || isNaN(i) == true)
{
alert("Dimensions can only be numbers!");
clearResult();
}
//check for negatives
if (x <= 0 || y <= 0 || z <= 0 || i <= 0)
{
alert("invalid dimension input, positive non-zero values only");
clearResult();
}
//if valid calculate tiles and print
else
tileCalculator();
}
function tileCalculator()
{
//take the input as variables
var tileWidth = document.getElementById("tile_width").value;
var tileHeight = document.getElementById("tile_height").value;
var wallWidth = document.getElementById("wall_width").value;
var wallHeight = document.getElementById("wall_height").value;
//find the areas of the tile and the wall
var tileArea = tileWidth * tileHeight;
var wallArea = wallWidth * wallHeight;
//divide these to find the number of tiles needed
var noOfTiles = (wallArea/tileArea);
//prints the result of noOfTiles
document.getElementById("result").innerHTML=" The number of Tiles you will need are : " + noOfTiles;
//scalled tiles to the canvas width of your choice
var scalledWidth = 500;
var ratioHW = wallHeight/wallWidth;
var scalledHeight = ratioHW*scalledWidth;
//scaled tile sizes
//scale the tiles to correct pixels
var scalledTileWidth = (tileWidth/wallWidth)*scalledWidth;
var scalledTileHeight = (tileHeight/wallHeight)*300;
//finds the number of tiles needs in a row
var noWidth = wallWidth/tileWidth;
//number of tiles in a column
var noHeight = wallHeight/tileHeight;
var canvas = document.getElementById("myCanvas");
canvas.style.width=scalledWidth + "px";
canvas.style.height=scalledHeight + "px";
printWall(0,0,noWidth,scalledTileWidth,(scalledTileHeight/2),noHeight);
}
//print a tile given the position and dimensions
function printTile(x,y,tileWidth,tileHeight)
{
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillRect(x,y,tileWidth,tileHeight);
}
//prints one row of tiles given the starting position and number to be printed
function printTileRow(x,y,numberOfTiles,tileWidth,tileHeight)
{
var start = 0;
//loops upto number of tiles in a row
while (start < numberOfTiles)
{
//prints a tile each time
printTile(x,y,tileWidth,tileHeight);
//next brick position
x = x + (tileWidth + 1); // add a space between tiles here.
start++;
}
}
//prints the wall
function printWall(x,y,numberOfTiles,tileWidth,tileHeight,numberOfRows)
{
//holds whether last row was shifted
var shiftCount = 0;
//starting index
var start = 0;
//loop up adding a row until required number of rows
while (start < numberOfRows)
{
//prints half a tile at the start of each row
printTile(0,y,(0.5 * tileWidth - 1),(tileHeight));
//prints the row
printTileRow((x+shiftCount),y,numberOfTiles,tileWidth,tileHeight);
//if shifted
if (shiftCount > 0)
{
//was shifted last row
shiftCount = 0;
}
else
{
//was not shifted last row
shiftCount = shiftCount + (0.5*tileWidth);
}
start++;
//start next row
y = y + (tileHeight + 1);
}
}
//clears the canvus each time the button is pressed
function clearCanvas()
{
//reset canvus to 300 by 300 and clear
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext('2d');
canvas.style.height="300px";
canvas.style.width="300px";
context.clearRect(0,0,300,300);
}
function clearResult()
{
document.getElementById("result").innerHTML="";
}
</script>
</body>
I would really appreciate it if someone could have a quick look for me! Thanks,
Try using onclick="javascript:validate();" on the form tag instead of on the button tag and try using 'onsubmit' instead of 'onclick'
Just replace your onclick attribute by onclick='validate(); return false'.
OR (better then previous)
Just add a type="button" attribute to your button tag, once the HTML5 button's default behavior is to submit forms.
Useful tip
Bind your handler programatically, this way (with no jQuery):
<button type="button" id="calculate"> Calculate </button>
...
window.addEventListener("load", function(){
document.getElementById("calculate").addEventListener("click", validate);
});
there is no problem with kepping the button in the form you you need to return false everytime to avoid the form submit using the return false like this
onclick="javascript:validate();return false;"