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
Related
I've got this function to modify a string to a USD-like format
function formatAmount(el){
var val = el.value;
//Only Numbers
val = val.replace(/[^0-9]/gi, '');
// Pad with Zeros
val = val.padStart(3,0);
// Value with Period
val = val.slice(0, -2) + '.' + val.slice(-2);
// Append $
val = '$' + val;
console.log( val );
//el.value = val; // Breaks??
}
<input type="text" onkeyup="formatAmount(this);" />
When formatting the value, it works just fine: Typing 12345 into the input will log $123.45. As soon as I change the value with el.value = val;, the function seems to get a little weird, and I can't quite figure out why. 12345 now returns $0123.45 if you type fast or $00123.45 if you type slowly. Why is is appending the 0's to the string when changing the field value, but not when logging it without changing?
Edit:
Based on what #Dennis mentioned, wrapping it in a typing-timeout function seems to work, as long as the timeout is sufficiently high. 10ms doesn't work, but 100ms seems to? This doesn't seem very elegant, however:
var formatTimeout = null;
function formatAmount(el){
clearTimeout(formatTimeout);
formatTimeout = setTimeout(function(){
var val = el.value;
//Only Numbers
val = val.replace(/[^0-9]/gi, '');
// Pad with Zeros
val = val.padStart(3,0);
// Value with Period
val = val.slice(0, -2) + '.' + val.slice(-2);
// Append $
val = '$' + val;
//console.log( val );
el.value = val; // Breaks??
}, 100);
}
The function gets triggered at every key press.
If you type in 12345, it will get triggered 5 times.
Here's what your value will look like if typing sufficiently slowly:
1, the function will change it to $0.01
2, it gets added at the end of the existing string to make it $0.012, which gets formatted by the function as $00.12
3, the initial string will be $00.123, and it will get formatted as $001.23.
...
The final result will be $00123.45.
There are a few ways to deal with this problem. The simplest solution would be to trim the initial 0s to keep your number clean, right before padding with zeros.
This difference between results while console.log and actually assigning the value is because the input to the formatAmount function is different each time.
When you set the value of the input field, this is what happens;
-> User enter `1`
-> formatAmount takes the value, converts it to $0.01 and *sets the value* to the input box
-> user enter `2`
-> formatAmount takes the value ($0.012), converts it to $00.12 and *sets the value* to the input box
This continues until you finish 12345 and get $00123.45. This happens because the two 0s you added in the start never vanish after the first 1 is typed.
Also, console.log works fine because everytime, the value received is 1, 12,...12345. The logic works fine for these. Only fails when you set the value back
A keyup action in javascript seems to work fine. Tested with various speeds and works like a charm. Also, try pasting numbers and use regex to remove leading 0's like
var textInput = document.getElementById('hello');
textInput.onkeyup = function (e) {
formatAmount(textInput.value);
};
function formatAmount(el){
var val = el;
//Only Numbers
val = val.replace(/[^0-9]/gi, '');
// Pad with Zeros
val = val.padStart(3,0);
// replace leading 0's
val = val.replace(/^0+/, '');
// Value with Period
val = val.slice(0, -2) + '.' + val.slice(-2);
// Append $
val = '$' + val;
textInput.value = val;
}
<input type="text" id="hello" />
Just to show an alternative starting point using Intl.NumberFormat.prototype.format(). Feel free to adjust to your requirements.
function formatAmount(el){
el.value = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumIntegerDigits: 3 }).format(parseFloat(el.value.indexOf('$') === 0 ? el.value.substr(1) : el.value));
}
<input type="text" onblur="formatAmount(this);" />
My guess is that your function is being executed multiple times at the same time, the first execution is not even finished before the next one starts. You need to check if the function is already running.
A simple javascript logical operator validation is not working for me.
eg. Target Price should not be greater than orginal price
x = input from user;
y = 1000; // fixed
if(x > 1000 )
{
alert ( x+'should not be greater than'+y);
}
else
{
alert ( ' proceed' );
}
here is my EXAMPLE
Those values are of type string, you need to convert them to number. You can use Number() for that.
targetPrice = Number($('#pdiwap_dropamt').val());
orginalPrice = Number($('#orgprice_wap').val());
You are compering two strings. Use something like this
if (parseInt(targetPrice) > parseInt(orginalPrice))
Because both the operands string so it does a string comparison.
You can convert the values to a number and then do the comparison like
targetPrice = +$('#pdiwap_dropamt').val();
orginalPrice = +$('#orgprice_wap').val();
Just use the parseInt function to validate correctly. Bucause html input gives the value in string format.
if (parseInt(targetPrice,10) > parseInt(orginalPrice,10))
Updated Link
I think the problem is from the input you're getting which is seen as a string. Try converting to integer first before comparing.
e.g x = parseInt(Input from user);
Yes! it input value is a string so its not validate properly.
Try This.
var x = document.getElementById("input").value;
var y = 1000;
if(!isNaN(x) && x < 1000) {
alert ('proceed' );
} else {
alert(x+'should not be greater than'+y);
}
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.
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.
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);