javascript input field to number - javascript

I need to convert an input field into a number. So if the input field is empty, or contains letters, the number would be 0.
This doesn't work:
var trade_gold = document.getElementById('trade_gold').value;
if (trade_gold < 1) {
I've tried parseInt on it too, can't seem to work it. Any advice?

var val = document.getElementById('trade_gold').value,
trade_gold = parseFloat(val) || 0;

var value = document.getElementById('trade_gold').value;
value = parseInt(value, 10);
// parseInt will return NaN if the conversion failed
if (isNaN(value)) {
value = 0;
}
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt

var trade_gold = 0;
try{
trade_gold = parseInt(document.getElementById('trade_gold').value, 10);
}catch(e){}

this will checks whether the it's a number or not, and change the value to 0 if it's not.
var trade_gold = document.getElementById('trade_gold').value;
if (trade_gold.search(/[^0-9]/)>=0)
{
// not a number
trade_gold = 0;
}

Related

How to remove NaN when there's no value entered in a field while calculating using Javascript

var discount_amount = parseFloat($('#amtdelivary').val());
var other_discount = parseFloat($('#othdis').val());
calculate_total_amount=Math.round(sub_total1 + tax_amount +discount_amount-other_discount);
$('#fnltot').val(calculate_total_amount);
When I keep the other_discount text field empty, its showing a NaN. If the text field is 0 its functioning accurately but when the field is set to empty, its resulting in NaN.
if(isNaN(other_discount)){
other_discount=0;
}
I tired these but its not working.
Append || 0 after your parseFloat like below. If value returned as NaN or any falsy value then it will return 0 instead of NaN.
var discount_amount = parseFloat($('#amtdelivary').val()) || 0;
var other_discount = parseFloat($('#othdis').val()) || 0;
var discount_amount = parseFloat();
console.log(discount_amount);
// Your if condition should also work.
if(isNaN(discount_amount)) {
discount_amount = 0;
}
console.log(discount_amount);
// Alternate and single line solution.
discount_amount = parseFloat() || 0;
console.log(discount_amount);
In java script simple you can pass parameter in given function if true then NUMBER and if false then NOT A NUMBER.
function IsNaN(value) {
if (Number.isNaN(parseInt(value)) === true)
return true;
return false;
}
Try this
if (other_discount == '' || other_discount == null) {
other_discount = 0
}

Javascript: Get Length of a String without Length Propery, And with Slice

I know, it's a weird one! But why does this not work?
function getStringLength(string) {
// see how many substrings > 0 can be built
// log that number & return
var subString = string.slice();
var counter = 0;
while (subString !== '') {
counter++;
subString = subString.slice(counter);
}
return counter;
}
var output = getStringLength('hello');
console.log(output); // --> expecting 5, but getting 3 (??)
I really want to do it with slice! The original challenge was to not use the length property, and I figured this out, which works fine:
function getStringLength(string) {
var long = 0;
while (string[long] !== undefined) {
long++;
}
return long;
}
you were mutating your string, this should work for you
function getStringLength(string) {
// see how many substrings > 0 can be built
// log that number & return
var subString = string.slice();
var counter = 0;
while (subString !== '') {
counter++;
subString = subString.slice(1);
}
return counter;
}
var output = getStringLength('hello');
console.log(output); // 5
The main difference was that I was doing
subString = subString.slice(1);
instead of
subString = subString.slice(counter);
which always decreased length by 1
The problem is the code substring.slice(counter) First time, you chop off 1 character. Then you chop off 2 characters from the already-chopped substring. Either chop off 1 at a time, or chop off the increasing amount from the original string. So that's either substring.slice(1) or string.slice(counter)
function getStringLength(string) {
// see how many substrings > 0 can be built
// log that number & return
var subString = string.slice();
var counter = 0;
while (subString !== '') {
counter++;
subString = substring.slice(1);
}
return counter;
}
var output = getStringLength('hello');
console.log(output);
To achieve expected result, use below option
function getStringLength(arr){
return arr.lastIndexOf(arr.slice(-1))+1
}
var output = getStringLength('hello');
console.log(output);
https://codepen.io/nagasai/pen/gGPWEE?editors=1111
Option2: As type of array is object,below option works too
function getStringLength(arr){
return Object.keys(arr).pop()*1 + 1
}
var output = getStringLength('hello');
console.log(output);
https://codepen.io/nagasai/pen/PJZmgg?editors=1111
Check the below updated options to handle empty and numbers
https://codepen.io/nagasai/pen/GMoQgy?editors=1111
https://codepen.io/nagasai/pen/YrweWr?editors=1111
Perhaps a slightly shorter answer:
function getStringLength(string) {
var counter = 0;
while (string.slice(counter)) {
counter++;
}
return counter;
}
var outputHello = getStringLength('hello');
console.log(outputHello); // 5
var outputEmpty = getStringLength('');
console.log(outputEmpty); // 0

Calculate values only for specific values

I have function that calculates difference between current and previous rows
Here it is
function distanceDifference() {
var rowsDistance = $('#tbody tr');
for (j = 1; j < rowsDistance.length; j++) {
// Get the rows
var previousDistanceRow = rowsDistance.eq(j - 1);
var currentDistanceRow = rowsDistance.eq(j);
var previousDistance = previousDistanceRow.find('td').eq(5).text();
var currentDistance = currentDistanceRow.find('td').eq(5).text();
//alert(previousDistance);
var difference = currentDistance - previousDistance;
//alert(difference);
currentDistanceRow.find('td').eq(6).text(difference);
}
}
It works well for all values
But I have column
<td id="dataType">#data.Datatype</td>
Value of it can be 0,1,2
I need to calculate difference only if it ===2
I try to do it like this
function distanceDifference() {
var rowsDistance = $('#tbody tr');
for (j = 1; j < rowsDistance.length; j++) {
var value = $('#dataType').text();
if (value === 2) {
// Get the rows
var previousDistanceRow = rowsDistance.eq(j - 1);
var currentDistanceRow = rowsDistance.eq(j);
var previousDistance = previousDistanceRow.find('td').eq(5).text();
var currentDistance = currentDistanceRow.find('td').eq(5).text();
//alert(previousDistance);
var difference = currentDistance - previousDistance;
//alert(difference);
currentDistanceRow.find('td').eq(6).text(difference);
}
}
}
but it not works. How I need to write code correctly?
Use if (value == 2) instead of if (value === 2).
Because equality operator === compares also the operands data types.
But the data type for the value '2' is string and you comparing with integer 2
Operator == will compare only value 2 == 2, without comparing the operands data types!
Even though a non-strict comparison would work it is - in my opinion - better practice to validate and convert user input to a specific data type.
So if you expect the users input to be an integer, use this
var value = parseInt( $('#dataType').text(), 10 );
If you expect it to be a number with a floating point, use this instead:
var value = parseFloat( $('#dataType').text() )
Then you can use a strict comparison like you already did.
But always validate if the user input has the right format.
So trouble was in that I get only first value from column
Here is valid code
function distanceDifference() {
var rowsDistance = $('#tbody tr');
for (j = 1; j < rowsDistance.length; j++) {
//var value = parseInt($('.dataType ').html());
var test = $('.dataType');
if (parseInt($(test[j]).html()) === 2) {
// Get the rows
var previousDistanceRow = rowsDistance.eq(j - 1);
var currentDistanceRow = rowsDistance.eq(j);
var previousDistance = previousDistanceRow.find('td').eq(5).text();
var currentDistance = currentDistanceRow.find('td').eq(5).text();
var difference = currentDistance - previousDistance;
currentDistanceRow.find('td').eq(6).text(difference);
}
}
}

checking for a value in an array

My function to check if a value is in an array returns false every time, even if it should be true.
When I change var value to be, let's say 20, and I run the page until 20 appears in the array, it works and returns true. However when the value is the prompt, and I type in a number that appears in the array, I always get false.
function checkIfInArray(n, anArray) {
return anArray.indexOf(n) > -1;
}
var array = new Array();
for (var i = 0; i < 10; i++) {
array[i] = Math.floor(Math.random() * 101);
}
alert("The array is " + array);
var value = prompt("Enter a value to check if it is in the array");
var result = checkIfInArray(value, array);
alert(result);
Your array contains numbers, prompt() returns a string. You need to convert the string into a number, which you can do with parseInt().
function checkIfInArray(n,anArray) {
return anArray.indexOf(n) > -1;
}
var array=new Array();
for (var i = 0; i < 10; i++)
{
array[i] = Math.floor(Math.random()*101);
}
alert("The array is " + array);
var value=parseInt(prompt("Enter a value to check if it is in the array"), 10);
var result=checkIfInArray(value,array);
alert(result);
Try like this
function checkIfInArray(n,anArray) {
return anArray.indexOf(parseInt(n)) > -1; // parse int . here was the problem
}
var array=new Array();
for (var i = 0; i < 10; i++)
{
array[i] = Math.floor(Math.random()*101);
}
alert("The array is " + array);
var value=prompt("Enter a value to check if it is in the array");
var result=checkIfInArray(value,array);
alert(result);
You have a type issue, the prompt result is a string not an int and the indexOf method use a strict mode to compare the elements, so you should cast the value to an int before call indexOf:
return anArray.indexOf(parseInt(n)) > -1;
*Note that the Array.indexOf is not supported in IE8
You're probably getting that error because the prompt is sending a string and not a number. Try using parseInt() to convert the string to an integer to test the value.
You could do either
var value = parseInt(prompt("Enter a value to check if it is in the array"));
or
var result = checkIfInArray(parseInt(value), array);

jquery counting inside input with custom value

I have a basic counter that counts up within an input field. this works exactly how I want it to. The problem I am facing is that I can only set the target number via the input value. i want to be able to set this via a js variable, ignoring the html input value
DEMO http://jsfiddle.net/vyN6V/238/
Current jQuery
var number = 827;
function count(Item){
var current = parseInt(Item.val());
Item.val(current +=5);
if(current < number){
setTimeout(function(){count(Item)}, 0.1);
}
}
count($(".input"));
Desired jQuery (doesn't work)
var number = 827;
var aValue = 500;
function count(Item){
var current = aValue;
Item.val(current +=5);
if(current < number){
setTimeout(function(){count(Item)}, 0.1);
}
}
count($(".input"));
Should work, you just forgot to add 5 to aValue:
var current = aValue;
aValue+=5;
Your current is inside your function, it works if you simply use aValue:
Item.val(aValue += 5);
Fiddle
this would solve the problem: http://jsfiddle.net/Jg6LN/1/
var number = 827;
var aValue = 500;
function count(Item, value){
var current = value || parseInt(Item.val());
Item.val(current +=5);
if(current < number){
setTimeout(function(){count(Item)}, 0.1);
}
}
count($(".input"), aValue);
What about this?
var aValue = 500;
var number = 827;
function count(Item) {
var current = parseInt(Item.val()) || aValue;
Item.val(current + 5);
if (Item.val() < number) {
setTimeout(function () {
count(Item)
}, 0.1);
}
}
count($(".input"));
http://jsfiddle.net/vyN6V/242/

Categories

Resources