Input value still a string after parsing to float - javascript

I don't know where am I failing. I am trying a simple thing: retrieve an input, parse it to float and do a calculation with that value (introduced by the user), but yet, it returns NaN.
Here it is the input (I make a string replace of commas to dots in my code, but right now I am just trying the simplest way in the Firebug console):
<input id="percent_31" class="form-control input-sm text-right" type="text" name="percent[31]" value="-3.3333">
This is what I am trying:
var percent = parseFloat($('#percent_31').val()).toFixed(2);
console.log(percent);
console.log(jQuery.type(percent));
/*This returns -3.33 and string type*/
console.log((100 + percent)/100);
/*This, as expected, returns NaN*/
This, on the other hand, works.
percent = -3.33;
console.log(percent);
console.log(jQuery.type(percent));
/*This returns -3.33 and number type*/
console.log((100 + percent)/100);
/*This returns what I need: 0.9667*/

If you want to round up to two decimals:
> percent = "-3.33678";
'-3.33678'
> typeof(percent);
'string'
> percent = Number(parseFloat(percent).toFixed(2));
-3.34
> typeof(percent);
'number'
If you want to truncate the decimals and not round them:
> percent = "-3.33678";
'-3.33678'
> typeof(percent);
'string'
> percent = Number(percent.slice(0, (percent.indexOf(".")) + 3));
-3.33
> typeof(percent);
'number'

You can use 'Number()'
var values = $('#percent_31').val();
var percent = Number(parseFloat(values).toFixed(2));
console.log(percent);
//console.log(jQuery.type(percent));
/*This returns -3.33 and string type*/
console.log((100 + percent)/100);
/*This, as expected, returns NaN*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="percent_31" class="form-control input-sm text-right" type="text" name="percent[31]" value="-3.3333">

create a variable and assign value to that variable.
var myvalue = $('#percent_31').val();
var percent = parseFloat(myvalue).toFixed(2);
console.log(percent);

The jQuery method val() is returning an string, so you can use Number() to work with the numerical value:
var val = $('#percent_31').val(),
percent = Number(parseFloat(val).toFixed(2)),
result = (100 + percent) / 100;
console.log('percent:', percent);
console.log('type:', $.type(percent));
console.log('result:', result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="percent_31" class="form-control input-sm text-right" type="text" name="percent[31]" value="-3.3333">

Related

javascript on input field addition

//// JavaScript function to add input values display into another input field
function calculate() {
var x = document.getElementById('fee_selector_holder').value;
var y = document.getElementById('content').value;
var result = document.getElementById('result');
var myResult = x + y;
result.value = myResult;
}
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
I am giving values to input fields its adding concatination but not adding please verify it on input function is correct or wrong once verify then reply me thats it my question.
You have strings, that is why it is concatenating. Make integers with:
http://www.w3schools.com/jsref/jsref_parseint.asp
And it will work well.
First, when you read values from DOM, they are read as string. You will have to use parseInt or parseFloat to convert string to integer.
Second, + operator has a override function for string to act as concatenation operator.
Also notice, I have used .value || 0. Here if value does not exist, performing arithmetic operation over it will return NaN so adding default value (0).
//// JavaScript function to add input values display into another input field
function calculate() {
var x = document.getElementById('fee_selector_holder').value || 0;
var y = document.getElementById('content').value || 0;
var result = document.getElementById('result');
var myResult = parseInt(x) + parseInt(y);
result.value = myResult;
}
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
You have to parse the input values to integer as all input values are string by default:
//// JavaScript function to add input values display into another input field
function calculate() {
var x = document.getElementById('fee_selector_holder').value || 0; // default value 0 if input is blank
var y = document.getElementById('content').value || 0; // default value 0 if input is blank
var result = document.getElementById('result');
var myResult = parseInt(x, 10) + parseInt(y, 10); // parse it here
result.value = myResult;
}
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
You should add attribute to result
result.setAttribute("value", myResult);

jQuery change text box value not working

I'm trying to display total price in sum label by multiplying qtyTxt value (user entered) with price. But it doesn't work, the if statement is never reached.
<input type="text" name="qtyTxt" value="1" size="2" style="width: 25px"/>
<label id="price">${adClicked.price}</label>
<label id="sum">${adClicked.price}</label>
<input type="hidden" name="id" value="${adClicked.id}"/>
<script>
$(".qtyTxt").bind('change', function () {
var sum=$(("#price").val())* ($(this).val());
$("#sum").val('Rs.'+sum);
});
</script>
There are no errors in the console and $("#sum").val('Rs.'+sum); works fine.
1) Use parseInt() or parseFloat() The parseInt() function parses a string and returns an integer.
2) Another mistake Don't use val() for label instead of use text() for label
var sum= parseInt($("#price").text() , 10) * parseInt($(this).val() ,10);
code be
$(".qtyTxt").bind('change', function () {
var sum= parseInt($("#price").text() , 10) * parseInt($(this).val() ,10);
$("#sum").text('Rs.'+sum);
});
Two issue:
1) You have error in your code, $(("#price").val()) should be $("#price").text() or $("#price").html()
2) You need to parse the values before doing mathematical calculation:
var sum=parseInt($("#price").text(),10)*parseInt($(this).val(),10) ;

NaN when printing to console but typeof is number jquery

I'm implementing a timer, and trying to find out why I can't change the contents of my "min" input box when a number greater than 60 is entered in the input "sec" box. When I print the value of "mins", I get NaN, but when I print its type, I get that its a number. I'm just starting out with JavaScript, so any help would be appreciated. Thanks :)
jQuery:
$(function(){
$("#sec").change(function(){
if($("#sec").val() >= 60){
secs = parseInt( $("#sec").val() );
console.log("secs is " + secs );
if(secs < 0){
alert("Please enter a valid time interval");
$("#sec").val("");
return;
}
mins = parseInt( $("#min").val() );
console.log("mins is " + mins );
console.log(typeof mins);
hours = parseInt( $("#hour").val() );
days = parseInt( $("#day").val() );
secs = secs % 60;
mins = mins + Math.floor(secs/60);//can be > 60
console.log("mins is " + mins );
console.log(typeof mins);
hours += mins/60;
days += hours/24;
$("#min").val(mins);
$("#hour").val(hours + mins/60);
$("#day").val(days + hours/24);
}
});
});
html:
div class="left"></div>
<div class="center">
<h3> Please enter a time: </h3>
<form class="form-inline">
<div class="form-group col-xs-2">
<input id="day" class="form-control input-sm input" type="number" value="" name="Days" placeholder="Days">
</div>
<div class="form-group col-xs-2">
<input id="hour" class="form-control input-sm input" type="number" value="" name="Days" placeholder="Hours">
</div>
<div class="form-group col-xs-2">
<input id="min" class="form-control input-sm input" type="number" value="" name="Days" placeholder="Minutes">
</div>
<div class="form-group col-xs-2">
<input id="sec" class="form-control input-sm input" type="number" value="" name="Days" placeholder="Seconds">
</div>
Despite the name "not a number," typeof NaN is "number". Yes, really. :-) NaN, like Infinity, is of the number type. It's defined for numbers in IEEE-754 (the floating-point number format JavaScript and many other programming languages use; specifically, JavaScript uses what's now called the "binary64 subformat", aka "double-precision").
If you call parseInt on something it can't parse, it will return NaN. So for instance:
var n = parseInt("");
console.log(typeof n); // "number"
console.log(n); // "NaN"
If you want to use 0 for mins (et. al.) when it's blank, you can do that with JavaScript's curiously-powerful || operator:
mins = parseInt( $("#min").val() ) || 0;
That will give you the number parseInt returned, or 0 if parseInt returned 0 or NaN.
Side notes:
If you're going to use parseInt for user-generated input parsing, you probably want to use its second argument, which tells it what number base to use (10, for decimal). E.g., n = parseInt(str, 10). Otherwise, it tries to guess from the input (mostly, it treats strings starting with 0x as hex).
parseInt will happily ignore extra characters after a number. For instance str = "4 apples"; n = parseInt(str) gives us n = 4. If you don't want that behavior, you might use + (n = +str;) or Number (n = Number(str)), both of which consider the entire string. But they both also accept 0x at the beginning to mean hex, and don't support using a radix (number base).

inputs need to equal zero before action

how can i get each input to equal zero before it is touched so that i dont get an error until every input is completed and not have it show in the input field. Also this is for money and im struggling to get the two decimal point thing down. thank you
<td>Subtotal</td>
<td class="total" id="tot" for="tot">
<input type="total" id="total">
<script type="text/javascript">
function myFunction()
{
var answer = document.getElementById('total');
var n = 0
var x = document.getElementById('itemprice');
var y = document.getElementById('itemprice1');
var z = document.getElementById('itemprice2');
//var d = document.getElementsById('itemprice3');
// parseFloat converts to values, otherwise you'll concatenate the strings.
answer.value = parseFloat(x[0].value) + parseFloat(y[0].value) + parseFloat(z[0].value); // + d.value;
}
</script>
</td>
give the item prices a zero default value:
<input type="total" id="itemprice" value="0.00">

calculation based on input field for a result on the fly

This is an extension to this thread.
My situation:
I need a user to enter a decimal value (ie 0.05) and show a simple calculation on the fly as the user types (or pastes). The example shown works for whole numbers but not when a decimal is entered into the input field.
I need to display the result in multiple places. I assumed I could just update getElementById to getElementByClass but that didn't work.
My Code:
<input type="text" name="capname" id="numberField" value="0.07" maxlength="5" />
<span name="mpd" id="mpdresult" class="mpdresult" ></span>
<span class="mpdresult" ></span> (second display)
<script>
window.onload = function() {
var base = 500;
var numberField = document.getElementById('numberField');
numberField.onkeyup = numberField.onpaste = function() {
if(this.value.length == 0) {
document.getElementById('mpdresult').innerHTML = '';
return;
}
var number = parseInt(this.value);
if(isNaN(number)) return;
document.getElementById('mpdresult').innerHTML = number * base;
};
numberField.onkeyup(); //could just as easily have been onpaste();
};
</script>
please use
var number = parseFloat(this.value);
instead of
var number = parseInt(this.value);
use ParseFolat for Decimal Numbers
document.write(parseFloat("10.33") + "<br>");
ParseFloatSample
Use parseFloat instead of parseInt. http://jsfiddle.net/janCY/
there is no such function getElementByClass. There is getElementsByClassName, it returns array with elements. But why don't use JQuery?

Categories

Resources