Why this function return Nan error? - javascript

When I click "+ 1", then in the "0" appears "NaN". Why ?
HTML:
<table>
<tr><td id="run">0</td></tr>
</table>
+ 1
JS:
function plus(){
document.getElementById("run").innerHTML = ( document.getElementById("run").value + 1 );
}

It happens because value property can be applied only to input or select elements.
Pay attention that you need to convert your string value to numeric, otherwise you will get string concatenation. It can be done with parseInt or parseFloat functions.
var val = parseInt(document.getElementById("run").innerHTML, 10);
document.getElementById("run").innerHTML = ( val + 1 );

That's because:
document.getElementById("run").value
will be undefined and undefined + 1 == NaN.
Input boxes have a value property, but nodes like <td /> have .innerHTML() or .innerText().
Also, note that '0' + 1 == '01', so you have to do some casting as well:
parseInt(document.getElementById('run').innerHTML, 10) + 1;
The additional radix - 10 - is necessary to convert strings that may be interpreted as octal numbers :)

Try this
function plus(){
document.getElementById("run").innerHTML = parseInt( document.getElementById("run").value) + 1;
}

Because attribute values are always strings and string + 1 is a NaN in JavaScript.
To solve this, use string.toFloat():
function plus(){
document.getElementById("run").innerHTML = ( document.getElementById("run").value.toFloat() + 1 );
}
Or use parseInt():
function plus(){
document.getElementById("run").innerHTML = ( parseInt(document.getElementById("run").value) + 1 );
}
Or use the ~~() function as a trick, but this will result in a not readable source.

I guess this question still deserve a better answer, but I may be wrong. )
Let's check what happens in your plus function. First, you get an element by its id, with
var targetElement = document.getElementById('run');
It's actually a reference to the object of DOMElement type. Which is quite easy to see by checking its nodeType property.
if (targetElement.nodeType === 1) { alert("It's an element!"); }
DOM Elements have plenty of nice properties, but their nodeValue is always equal to null. So if you want to work with its text content, you can either look for the child textNodes - or just use innerHTML property. It's a string, yes, but Javascript will manage to convert it to a normal number if it's numeric (and 0 is numeric, from what I remember :).
So your plus function can be actually written just like this (the proof):
document.getElementById('run').innerHTML++;

Because value is a property of HTMLInputElement and the TD element is not an HTMLInputElement but a HTMLTableCellElement, so doesn't have that property and:
undefined + 1; // NaN - Not a Number
You can basically use the same innerHTML property you used to set the content also to get it:
function plus() {
// no need to execute `getElementById` twice
var td = document.getElementById("run");
td.innerHTML = +td.innerHTML + 1;
}
To convert the value in Number I used the unary plus operator. You could also check if it's NaN before use it, something like:
function plus() {
var td = document.getElementById("run");
var value = +td.innerHTML || 0;
td.innerHTML = value + 1;
}
In that case if it's NaN (or 0, but in that case it's an identity) will set to 0, and the count will start from 1 without give any error.
Additionally, I would say that it could be better use the textContent property where supported, but then the code will be a bit more complex to handle all browser's (e.g. in some IE versions you need to use innerText instead), and innerHTMLcould be good in most of the cases.

Related

get input value with math function in variable

I've got some javascript to change the input value via plus/minus buttons.
I now need to save the value after the value has been decremented in a variable and output it as a number.
The javascript for the decrement looks something like this:
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[id='+fieldName+']').val(currentVal - 1);
var test = parseInt($('input[id='+fieldName+']').val(currentVal - 1).val());
alert(test);
}
So as you can see I'm trying to get the updated value of the input in a variable called 'test', but all I'm getting is a NaN. Any ideas how to output the updated value of the input as a number within my test variable?
As #trincot said we cannot re-produce your situation. But the reason a NaN would be returned is because.
parseInt Returns an integer number parsed from the given string. If the first character cannot be converted to a number, NaN is returned.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
let a = '1'
let b = 'Two'
console.log(parseInt(a));
// 1
console.log(parseInt(b));
// NaN
console.log(parseInt(undefined))
// NaN
You can use double Tilda operator ~~ which behaves like Math.floor() except will return you 0 if the value is not a number.
I believe this is the solution you are looking for:
let inputField = document.querySelector('input[name="fieldName"]');
increment = () => {
let currentValue = ~~inputField.value;
alert(currentValue);
inputField.value = currentValue + 1;
};
decrement = () => {
let currentValue = ~~inputField.value;
alert(currentValue);
if (currentValue > 0) {
inputField.value = currentValue - 1;
}
};
<input type="number" name="fieldName" value="0" />
<button onclick="increment()">+</button>
<button onclick="decrement()">-</button>
Hope this helps,
Something showed up to me.
You are using jquery (I think it's right cause of the $ selector), and you are getting the ID with bracket notation.
Why not using something like
var selector = '#' + fieldName;
Then
$(selector)???
Another thing, usually when I'm trying something with javascript, I try it into the developer tool's console of my browser.
Doing it step by step avoid mistakes

parseInt doesn't work

in my current source code textbox value is 1.
when I try alert(isNaN(obj.text()) it returns false that is expected but after parseInt when I write alert(a); it returns NaN
minus.click(function () {
var a = 1; if (!isNaN(obj.text())) a = parseInt(obj.text());
if (a > 1) a -= 1; obj.text(a);
});
what is the problem?
Edit: this is the full code:
<input type="text" class="basket-txt" value="1" />
jQuery.fn.basket = function (options) {
var defaults = {
}
options = jQuery.extend(defaults, options);
this.each(function () {
var $this = $(this);
$this.height(32).css({ 'line-height': '32px', 'font-weight': 'bold', 'width':'40px', 'text-align':'center', });
var tbl = $('<table border="0" style="border-spacing:0px;float:left;">').appendTo($this.parent());
var tr1 = $('<tr>').appendTo(tbl);
var plus = $('<div class="basket-plus">');
$('<td>').append(plus).appendTo(tr1);
$('<td>').append($this).appendTo(tr1);
var minus = $('<div class="basket-minus">');
$('<td>').append(minus).appendTo(tr1);
var tr2 = $('<tr>').appendTo(tbl);
$('<td>').appendTo(tr2);
$('<td>').appendTo(tr2).append($('<div>').addClass('add-to-basket'));
$('<td>').appendTo(tr2);
$this.keypress(function (e) { if (e.which < 48 || e.which > 57) e.preventDefault(); });
minus.click(function () {
var a = 1; if (!isNaN($this.text())) a = parseInt($this.text());
if (a > 1) a -= 1; $this.text(a);
});
plus.click(function () {
var a = 1; if (!isNaN($this.text())) a = parseInt($this.text());
if (a < 1000000) a += 1; $this.text(a);
});
});
}
actually I knew I could correct the code and it would work my concern was to understand why isNaN returns false but parseInt returns NaN
The jQuery text() method will take all the descendent text nodes of an element and combine them into a single string.
An input element can't have descendant nodes of any kind. Its current value is exposed via the value property, which you can read with the val() method in jQuery.
You shouldn't use parseInt without a radix, especially with free form input. You might get octal or hex data instead of a decimal.
parseInt($this.val(), 10)
You get the value of an <input> with .val(), not .text().
The isNaN() function returns false for isNaN(""). Why? Because when "" (the empty string) is converted to a number, it's 0. Pass a non-number to isNaN() and the first thing it does is coerce the value into a number.
It's kind-of pointless to try isNaN() before parseInt() anyway, since parseInt() will tell you when it can't parse a nice-looking integer. Note however that parseInt() doesn't care if there's garbage at the end of the input.
If you want to convert a string to a number when it's a valid string representation of a number, and NaN when it isn't, you can use
var myNumber = +myString;
That'll accept numbers with fractional parts and exponents too, so you'd have to either truncate that to just an integer or check to see if it is one:
var myNumber = +myString;
if (isNaN(myNumber))
// not a valid number
else if (myNumber !== Math.floor(myNumber))
// not an integer
else
// yaay!
minus.click(function () {
// let's parse the integer first
var num = parseInt( obj.val(), 10 );
// then later, we can check if it's NaN
if ( !isNaN(num) && num > 1 ) {
num -= 1;
obj.val(num);
}
});
actually I knew I could correct the code and it would work my concern was
to understand why isNaN returns false but parseInt returns NaN
isNaN doesn't work the way it should. There is type coercion going on.
isNaN will convert the value to a number first. An empty string will be converted to a 0
Number("") === 0; // true
0 is obviously not NaN, so it returns false.
parseInt doesn't do type coercion, it parses the value differently.
Check this question and this other question for reference.
parseInt returns NaN when the first non-whitespace character cannot be converted to a number.

Simple math in jquery

I am reading a select form value and multiplying it by 50 in jquery. I need to add a value of 1 to the qty that is returned by the select menu every time before multiplying by 50. How would I do that? The offending code looks like this.
$('#selectform').val() *50);
If I use
$('#selectform').val() +1 *50);
The result is not correct.
Parentheses should be used.
($('#selectform').val()*1 + 1) *50;
Your current expression is interpreted as:
var something = $('#selectform').val();
var another = 1 * 50;
var result = something + another
The *1 after .val() is used to convert the string value to a number. If it's omitted, the expression will be interpreted as:
var something = $('#selectform').val() + "1"; //String operation
var result = something * 50; // something is converted to a number, and
// multiplied by 50
Correct parentheses and use parseInt function -
(parseInt($('#selectform').val(),10) +1) *50;
The data from $('#selectform').val() is probably being treated as a string.
Use parseInt($('#selectform').val()) to convert it to an int before the multiply.
You should have a look at the operator precedence in JavaScript.
You need to force the addition to happen before the multiplication with parentheses:
bar myVal = ($("#selectform").val() + 1) * 50;

How to parse float with two decimal places in javascript?

I have the following code. I would like to have it such that if price_result equals an integer, let's say 10, then I would like to add two decimal places. So 10 would be 10.00.
Or if it equals 10.6 would be 10.60. Not sure how to do this.
price_result = parseFloat(test_var.split('$')[1].slice(0,-1));
You can use toFixed() to do that
var twoPlacedFloat = parseFloat(yourString).toFixed(2)
If you need performance (like in games):
Math.round(number * 100) / 100
It's about 100 times as fast as parseFloat(number.toFixed(2))
http://jsperf.com/parsefloat-tofixed-vs-math-round
When you use toFixed, it always returns the value as a string. This sometimes complicates the code. To avoid that, you can make an alternative method for Number.
Number.prototype.round = function(p) {
p = p || 10;
return parseFloat( this.toFixed(p) );
};
and use:
var n = 22 / 7; // 3.142857142857143
n.round(3); // 3.143
or simply:
(22/7).round(3); // 3.143
To return a number, add another layer of parentheses. Keeps it clean.
var twoPlacedFloat = parseFloat((10.02745).toFixed(2));
If your objective is to parse, and your input might be a literal, then you'd expect a float and toFixed won't provide that, so here are two simple functions to provide this:
function parseFloat2Decimals(value) {
return parseFloat(parseFloat(value).toFixed(2));
}
function parseFloat2Decimals(value,decimalPlaces) {
return parseFloat(parseFloat(value).toFixed(decimalPlaces));
}
ceil from lodash is probably the best
_.ceil("315.9250488",2)
_.ceil(315.9250488,2)
_.ceil(undefined,2)
_.ceil(null,2)
_.ceil("",2)
will work also with a number and it's safe
You can use .toFixed() to for float value 2 digits
Exampale
let newValue = parseFloat(9.990000).toFixed(2)
//output
9.99
I have tried this for my case and it'll work fine.
var multiplied_value = parseFloat(given_quantity*given_price).toFixed(3);
Sample output:
9.007
parseFloat(parseFloat(amount).toFixed(2))
You have to parse it twice. The first time is to convert the string to a float, then fix it to two decimals (but the toFixed returns a string), and finally parse it again.
Please use below function if you don't want to round off.
function ConvertToDecimal(num) {
num = num.toString(); //If it's not already a String
num = num.slice(0, (num.indexOf(".")) + 3); //With 3 exposing the hundredths place
alert('M : ' + Number(num)); //If you need it back as a Number
}
For what its worth: A decimal number, is a decimal number, you either round it to some other value or not. Internally, it will approximate a decimal fraction according to the rule of floating point arthmetic and handling. It stays a decimal number (floating point, in JS a double) internally, no matter how you many digits you want to display it with.
To present it for display, you can choose the precision of the display to whatever you want by string conversion. Presentation is a display issue, not a storage thing.
#sd
Short Answer: There is no way in JS to have Number datatype value with trailing zeros after a decimal.
Long Answer: Its the property of toFixed or toPrecision function of JavaScript, to return the String. The reason for this is that the Number datatype cannot have value like a = 2.00, it will always remove the trailing zeros after the decimal, This is the inbuilt property of Number Datatype. So to achieve the above in JS we have 2 options
Either use data as a string or
Agree to have truncated value with case '0' at the end ex 2.50 -> 2.5.
You can store your price as a string
You can use
Number(string)
for your calculations.
example
Number("34.50") == 34.5
also
Number("35.65") == 35.65
If you're comfortable with the Number function , you can go with it.
Try this (see comments in code):
function fixInteger(el) {
// this is element's value selector, you should use your own
value = $(el).val();
if (value == '') {
value = 0;
}
newValue = parseInt(value);
// if new value is Nan (when input is a string with no integers in it)
if (isNaN(newValue)) {
value = 0;
newValue = parseInt(value);
}
// apply new value to element
$(el).val(newValue);
}
function fixPrice(el) {
// this is element's value selector, you should use your own
value = $(el).val();
if (value == '') {
value = 0;
}
newValue = parseFloat(value.replace(',', '.')).toFixed(2);
// if new value is Nan (when input is a string with no integers in it)
if (isNaN(newValue)) {
value = 0;
newValue = parseFloat(value).toFixed(2);
}
// apply new value to element
$(el).val(newValue);
}
Solution for FormArray controllers
Initialize FormArray form Builder
formInitilize() {
this.Form = this._formBuilder.group({
formArray: this._formBuilder.array([this.createForm()])
});
}
Create Form
createForm() {
return (this.Form = this._formBuilder.group({
convertodecimal: ['']
}));
}
Set Form Values into Form Controller
setFormvalues() {
this.Form.setControl('formArray', this._formBuilder.array([]));
const control = <FormArray>this.resourceBalanceForm.controls['formArray'];
this.ListArrayValues.forEach((x) => {
control.push(this.buildForm(x));
});
}
private buildForm(x): FormGroup {
const bindvalues= this._formBuilder.group({
convertodecimal: x.ArrayCollection1? parseFloat(x.ArrayCollection1[0].name).toFixed(2) : '' // Option for array collection
// convertodecimal: x.number.toFixed(2) --- option for two decimal value
});
return bindvalues;
}
I've got other solution.
You can use round() to do that instead toFixed()
var twoPlacedFloat = parseFloat(yourString).round(2)
The solution that work for me is the following
parseFloat(value)

How do I add an integer value with javascript (jquery) to a value that's returning a string?

I have a simple html block like:
<span id="replies">8</span>
Using jquery I'm trying to add a 1 to the value (8).
var currentValue = $("#replies").text();
var newValue = currentValue + 1;
$("replies").text(newValue);
What's happening is it is appearing like:
81
then
811
not 9, which would be the correct answer. What am I doing wrong?
parseInt() will force it to be type integer, or will be NaN (not a number) if it cannot perform the conversion.
var currentValue = parseInt($("#replies").text(),10);
The second paramter (radix) makes sure it is parsed as a decimal number.
Parse int is the tool you should use here, but like any tool it should be used correctly. When using parseInt you should always use the radix parameter to ensure the correct base is used
var currentValue = parseInt($("#replies").text(),10);
The integer is being converted into a string rather than vice-versa. You want:
var newValue = parseInt(currentValue) + 1
parseInt didn't work for me in IE. So I simply used + on the variable you want as an integer.
var currentValue = $("#replies").text();
var newValue = +currentValue + 1;
$("replies").text(newValue);
In regards to the octal misinterpretation of .js - I just used this...
parseInt(parseFloat(nv))
and after testing with leading zeros, came back everytime with the correct representation.
hope this helps.
to increment by one you can do something like
var newValue = currentValue ++;
Simply, add a plus sign before the text value
var newValue = +currentValue + 1;
Your code should like this:
<span id="replies">8</span>
var currentValue = $("#replies").text();
var newValue = parseInt(parseFloat(currentValue)) + 1;
$("replies").text(newValue);
Hacks N Tricks
var month = new Date().getMonth();
var newmon = month + 1;
$('#month').html((newmon < 10 ? '0' : '') + newmon );
I simply fixed your month issue, getMonth array start from 0 to 11.
You can multiply the variable by 1 to force JavaScript to convert the variable to a number for you and then add it to your other value. This works because multiplication isn't overloaded as addition is. Some may say that this is less clear than parseInt, but it is a way to do it and it hasn't been mentioned yet.
You can use parseInt() method to convert string to integer in javascript
You just change the code like this
$("replies").text(parseInt($("replies").text(),10) + 1);

Categories