I'm trying to use parseint but it does not work - javascript

I'm writing a script and I want a H1 tag to increase with an input's value. But it doesn't work. I'm probably dumb, but I'm here cause I want help.
This is my code:
var h1Value = 0;
function addFun() {
var changeH1By = document.getElementById('input').value;
parseInt('h1Value') + parseInt('changeH1By');
document.getElementById('h1').innerHTML = h1Value;
}
<h1 id="h1">0</h1>
<input type="number" id="input" value="1">
<button onclick="addFun()">Add</button>
As you probably see I'm using parseInt(), because else the h1 was "11". Like 1 + 1 = 11? Am I using the parseInt wrong or is something else wrong?
Thank you!

You were passing an string into parseInt, remove the quotes to pass the variable.
You didn't assign the result of parseInt('h1Value') + parseInt('changeH1By');to any variable
Instead off keeping track of var h1Value, lets use document.getElementById('h1').innerHTML to get the current value
Removed newValue so we can set the new value instant as innerHTML
function addFun() {
var currentvalue = document.getElementById('h1').innerHTML;
var changeH1By = document.getElementById('input').value;
document.getElementById('h1').innerHTML = parseInt(currentvalue) + parseInt(changeH1By);
}
<h1 id="h1">0</h1>
<input type="number" id="input" value="1">
<button onclick="addFun()">Add</button>

You're passing the strings "h1Value" and "changeH1By" to parseInt and it's trying to parse those literal strings to integers. If you try logging the result of e.g. parseInt("h1Value") it evaluates to NaN, i.e. "not a number", which would give you a hint of where you're going wrong.
A working version of your code would be
var h1Value = 0;
function addFun() {
var changeH1By = document.getElementById('input').value;
h1Value = h1Value + parseInt(changeH1By);
document.getElementById('h1').innerHTML = h1Value;
}
The type of h1Value is already a number, so it doesn't need to be coerced into one, and instead of calling parseInt with the literal string "changeH1By", you'll need to give the actual variable as an argument. Also the line
parseInt('h1Value') + parseInt('changeH1By');
doesn't do anything by itself, the javascript engine will just compute the value and throw it away, as you're not saving it into a variable etc.

A clean way for coding that...
<input..> elements of type="number" have a valueAsNumber property
use const to avoid repeating the results of these interpretations
const
h1_element = document.getElementById('h1')
, changeH1By = document.getElementById('input')
;
function addFun()
{
h1_element.textContent = changeH1By.valueAsNumber
+ parseInt(h1_element.textContent)
}
<h1 id="h1">0</h1>
<input type="number" id="input" value="1">
<button onclick="addFun()">Add</button>

Related

Values not being returned in JS

I have a value separated by commas. The code is as follows:
function addComma(values) {
const v = values.value && new Number(values.value.replace(/,/g, ''));
values.value = v.toLocaleString();
}
if (document.getElementById("values"))
var pay = document.getElementById("values").value;
payment = pay.replace(/\,/g, '');
<label>Rent</label> <input style="font-size:10px;width:80px;text-align:right" id="values" type="text" onkeyup="addComma(this);">
Issue:
if (selectedPayType === "A") {
PV = getNPV(rate, array, payment) + payment;
console.log("PV);
}
For some reason, PV returns the value but it doesn't add the +payment. But, instead of +payment, if i use the numeric value itself ex: 10000, then it adds the value up.
I tried debugging and it is taking the payment value inside the getNPV however, not adding it up which is really weird. Not sure what i am doing wrong here. Any help is appreciated. Thank you.
The main problem is that you are adding a string to a number . For eg: 1 + '2' = '12'. So you need to convert your payment which is a string, into a number.
Do not use Number constructor as it might cause unwanted results, but use parseFloat or parseInt to convert numeral strings into numbers.
p.s. for parseInt you should/need to specify a radix .
Useful links
parseInt()
parseFloat()
why avoid creating object versions of primitives
Changed a bit the structure ( added the if inside the addComma function that is called onkeyup )
See below
function addComma(values) {
const v = values.value && parseFloat(values.value.replace(/,/g, ''));
values.value = v.toLocaleString();
if (document.getElementById("values")) {
var pay = document.getElementById("values").value;
payment = pay.replace(/\,/g, '');
PV = 10 + parseFloat(payment);
console.log(PV);
}
}
<label>Rent</label> <input style="font-size:10px;width:80px;text-align:right" id="values" type="text" onkeyup="addComma(this);">

Formatting input type="text" in JS

I have a text field with type='text' and I am trying to format the text with commas. Example: 500000000 would become 500,000,000.
I have the following code:
function addComma(values) {
values.value = values.value.replace(",", "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
if (document.getElementById("values"))
payment = parseInt(document.getElementById("values").value);
<label1>Rent</label1> <input id="values" type="text" onkeyup="addComma(this);">
However, it's printing 5,000,0,0,0,000 and the formatting is off for some reason. I also tried .toLocaleString(), but that doesn't seem to work either. What am I doing wrong here?
I was referred to a few other posts on Stack Overflow, but nothing seems to work out.
function addComma(values) {
const v = values.value && new Number(values.value.replace(/,/g,''));
values.value = v.toLocaleString();
}
if (document.getElementById("values"))
payment = parseInt(document.getElementById("values").value);
<label1>Rent</label1> <input id="values" type="text" onkeyup="addComma(this);">
You can do this by converting the number to a string, then manually iterating over each character and find places where a comma is needed.
function formatNumber(number) {
var str = number.toString();
var offset = str.length % 3;
var newStr = '';
for (var i = 0; i < str.length; i++) {
if (i > 0 && i % 3 === offset) {
newStr += ',';
}
newStr += str[i];
}
console.log(str, '=>', newStr);
}
formatNumber(5);
formatNumber(50);
formatNumber(500);
formatNumber(5000);
formatNumber(50000);
formatNumber(500000);
formatNumber(5000000);
I'd recommend using a change event rather than a keyup event as change will only update the value when the input is no longer the focus. If you use keyup the code will try and reinterpret the new string you add back to the input as a number and throw an error.
Here's the code using toLocaleString (just press tab after adding the number as if to move to the next input box):
const values = document.querySelector('#values');
values.addEventListener('change', handleChange, false);
function handleChange(e) {
const value = Number(e.target.value);
const formatted = value.toLocaleString();
values.value = formatted;
}
<input id="values" type="text">
The other answers posted before this one using the input field are ok to show how it works, but they are bugged as soon as you enter a new number when it has formatted to a string using toLocaleString(). For that reason I added the toNumber() function to be complete. In the example below I preform the following steps:
When user fills in a number in the input field and leaves the input field: Call toString(e) and make from the entered number a formatted string.
If the user again selects the input field, call toNumber(e) and format it back to a number.
This makes sure you won't get NaN when reselecting or will become completely unusable.
The NaN property represents "Not-a-Number" value. This property indicates that a value is not a legal number.
It is still possible to add text in it, this will result in NaN as text cannot be formatted to a number. This could be filtered out in the toString(e) when necessary. I did this in the example below by adding if (formatted !== 'NaN') {} Only when it's not NaN it will set the value to the new formatted number. Else it won't do anything. Please note: a number with dots is a string in this case so wont work either.
const values = document.querySelector('#values');
values.addEventListener('click', toNumber, false);
values.addEventListener('focusout', toString, false);
function toNumber(e) {
const value = e.target.value;
const unformatted = value.replace(/\D/g,'');
values.value = unformatted;
}
function toString(e) {
const value = Number(e.target.value);
const formatted = value.toLocaleString();
if (formatted !== 'NaN') {
values.value = formatted;
}
}
<input id="values" type="text">
To fix that, you can also remove my addition and add a filter before the toString(e) does it's thing and filter the dots, text etc. so only the numbers remain.

my function() is not working or the value is not converting to a number

Been stuck here ALL day long trying to figure out what is wrong with my syntax.
Here’s my code… I’d like to verify if Number1 is > than Number 2. However, whenever I tried to run the code I always getting false.
Please help me..
PS. I am new to coding :(
var num1 = document.getElementById('num1');
var num2 = document.getElementById('num2');
var x = Number(num1);
var y = Number(num2);
function higherThan(x, y){
x > y? alert(true) : alert(false);
}
Numb1: <input type="number" id="num1"><br>
Numb2: <input type="" id="num2"><br>
<button onclick="higherThan();">Is Higher Than?</button>
Get the values of the inputs inside the function.In your case you are trying to get the value even before user have provided any input.
Also to get the value you need to do
document.getElementById('elemId').value
function higherThan(x, y) {
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
var x = Number(num1);
var y = Number(num2);
x > y ? alert(true) : alert(false);
}
Numb1:
<input type="number" id="num1">
<br> Numb2:
<input type="" id="num2">
<br>
<button onclick="higherThan();"> Is Higher Than ?</button>
a few things:
you are not passing anything to your higherThan() function when you call it, but you have defined higherThan() as requiring two arguments.
I'm not convinced you that num1 and num2 are actually numbers. I would use some console logs to verify that you are a.) getting something back here and b.) that what you are getting back is a number not a string. You may need to use parseInt as obviously you can't math with strings.
What is happening here? var x = Number(num1); the way this is written it looks like you are calling a function? where is this function defined?
I would test your code in jsfiddle or browser console first and verify it works before trying to embed it in a webpage.
You have to take the value from the control. You can pass the id's of the control's to refer that inside the function for getting the values. Try the following way:
function higherThan(n1, n2){
var x = Number(document.getElementById(n1).value);
var y = Number(document.getElementById(n2).value);
var res = x > y? true : false;
alert(res);
}
Numb1: <input type="number" id="num1"><br>
Numb2: <input type="" id="num2"><br>
<button onclick="higherThan('num1','num2');">Is Higher Than?</button>

trouble getting variable to display using .innerHTML

HTML:
<input type="number" id="input" placeholder="Number.." onkeydown="javascript:
return event.keyCode === 69 ? false : true"/>
<div class="boxes">
<div class="decimalBox">
<p>Decimal:
<span id="decimalOutput"></span>
</p>
</div>
<div class="binaryBox">
<p>Binary:
<span id="binaryOutput"></span>
</p>
</div>
Javascript:
//global variables
var number = document.getElementById('input');
var decimalOutput = document.getElementById('decimalOutput');
var binaryOutput = document.getElementById('binaryOutput');
number.addEventListener("input", toBinary);
//Converting Decical to Binary by using independent division and taking the
modulus the number
function toBinary(x){
var result = [], i;
for(var i=number;i>0;i=parseInt(i/2)){
result.push(i%2);
}
var binary = result.reverse().join('');
//returns the result of the array and then reverses the order to create the
correct binary order.
decimalOutput.innerHTML = number.value;
binaryOutput.innerHTML = binary;
return binary;
}
My question is this. Everything is working except for me being able to display the binary variable declared in the toBinary() Function. It seems to throw errors and not allow me to actually use that value to display the current input in binary form, however I tested this using parameters and the code runs just fine. I just need help figuring out why this specific case won't work.
Correct way to fix this was #titus suggestion: instead of having "var i = number" in the for loop change it to the value or number. Thanks!

store data from input form to var for javascript function

Hi I am learning javascript right now.
so I want to make a function that converts fahrenheit to celsius but with an input to store in variable and then shows the result with alert(result);
here's my code from my basic understanding
var f = document.getElementById("fa").value;
function toCelsius(f) {
var result = (5/9) * (f-32);
alert (result);
}
<p>calls a function to convert from Fahrenheit to Celsius:</p>
<form>
input fahrenheit :<input type="number" id="fa">
<button onclick="toCelsius(f)">submit</button>
</form>
everytime I input a number, the result does not change, I assume I'm wrong in .value or .innerHTML ?
<p>Calls a function to convert from Fahrenheit to Celsius:</p>
<form>
input fahrenheit :<input type="number" id="fa"/>
<button onclick="toCelsius()">submit</button>
</form>
<script>
function toCelsius() {
var f = document.getElementById("fa").value;
var result = (5/9) * (f-32);
alert (result);
}
</script>
Put the value check inside the function, with no parameters.
You need to use the variable, 'f' in your mathematical expression as a number. JavaScript will do type juggling for you, but since you are learning, it is good to know that there is a way to force it.
function toCelsius()
{
var f = parseFloat(document.getElementById("fa").value);
var result = (5/9) * (f-32);
alert (result);
}
or
function toCelsius()
{
var result = (5/9) * (parseFloat(document.getElementById("fa").value) - 32);
alert (result);
}
or
function toCelsius()
{
alert ((5/9) * (parseFloat(document.getElementById("fa").value) - 32));
}
=========
<button onclick="toCelsius(f)">submit</button>
This won't work because f is not in play at this time.
Call your handler, then grab the DOM values you need.
Your problem is here:
var f = document.getElementById("fa").value;
This creates a global variable with the current value of the element with ID fa. It does not change after that, so regardless of what you enter into the form, you'll get the same value.
You need to get the value of the input when the button is clicked, so:
Change the button to type button so that it doesn't submit the form
Pass the current value to the function so that it get's the right value
E.g.
function toCelsius(n) {
var result = (5/9) * (n-32);
alert (result);
}
<p>calls a function to convert from Fahrenheit to Celsius:</p>
<form>
input fahrenheit :<input type="number" id="fa" name="fa">
<button type="button" onclick="toCelsius(this.form.fa.value)">Calc value</button>
</form>
Note that the input must have a name to be successful (i.e. for its value to be submitted with the form). If you want the form to submit, set the button type back to submit (or remove the type since submit is the default).
You keep using
var f = document.getElementById("fa").value;
You need to convert f to integer or float format so use ParseInt if you want only integers or ParseFloat if you want integers and fractions.

Categories