Why is the '+' operator concating my numbers? - javascript

I want to access the values entered in the input box and then get their sum, but javascript is concatenating the result. Here is the code
<script>
$(document).ready(function(){
$( "#dateSelector" ).click(function(){
$(this).datepicker();
});
});
$(document).ready(function(){
$("#ocb750cb").click(function(){
var closingBal = 0;
var openingBal = document.getElementById("ocb750ob").value;
alert(openingBal);
Number(openingBal);
var stockBal = document.getElementById("ocb750sb").value;
alert(stockBal);
Number(stockBal);
var sold = document.getElementById("ocb750sl").value;
alert(sold);
var store = document.getElementById("ocb750cb");
store.value = (stockBal + openingBal) - sold;
});
});
</script>
<th class = "main brand">OCB 750</th>
<th class = "main"><input type="text" maxlength="5" id="ocb750ob"></th>
<th class = "main"><input type="text" maxlength="5" id="ocb750sb"></th>
<th class = "main"><input type="text" maxlength="5" id="ocb750tl"></th>
<th class = "main"><input type="text" maxlength="5" id="ocb750sl"></th>
<th class = "main"><input type="text" maxlength="5" id="ocb750rs"></th>
<th class = "main"><input type="text" maxlength="5" id="ocb750cb"></th>
suppose i enter 5 and 2 my output will be 52 and not 7, it is getting concatenated

You values have string format,you need use parceInt

The value of a textbox is text. You need to cast it to a number:
var openingBal = parseFloat(document.getElementById("ocb750ob").value);

You have to use parseInt(x) to be sure, that value is interpreted as integer. Otherwise javascript interpret it as string, so + operator is concatenating.
Use:
var openingBal = parseInt(document.getElementById("ocb750ob").value);
Etc.

var stockBal = document.getElementById("ocb750sb").value;
stockbal will be a string, so you have to parse it to get an integer
try{
var stockBalInt = parseInt(stockBal);
}catch(error){
-..handle error
}
Since you concatenate two strings together, "5" + "2" = "52"

You should use parseInt():
store.value = ( parseInt(stockBal) + parseInt(openingBal) ) - parseInt(sold);

I think it's because all the variables retrieved using getElementById("id").value are "string". Try to do like this:
var sold = parseInt(document.getElementById("id").value);
Hope this will help.

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);

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">

Removing commas in 'live' input fields in jquery

I have a series of input boxes in a table with some number of dynamically generated rows as such:
<table id="someDataTable">
<tbody>
<tr>
<td >Some Title</td>
<td >Units</td>
<td >Val/Unit</td>
<td >Value</td>
</tr>
<tr>
<td><input type="text" size="30" /></td>
<td><input type="text" size="14" class="units commas"/></td>
<td><input type="text" size="14" class="value commas"/></td>
<td><input type="text" size="14" readonly="readonly" class="autoTotal"/></td>
</tr>
...
</tbody>
</table>
Now, I have a blur() call to add commas every time an input box is exited to add commas with the nifty Number Formatter plugin, and it simply does this:
<script>
$(".commas").blur(function () {
$(this).parseNumber({ format: "#,###", locale: "us" });
$(this).formatNumber({ format: "#,###", locale: "us" });
});
</script>
And it works beautifully. Now, on the other side, I also have a chunk of code that does the form math automatically on every keystroke. It has a call in initialize() that looks like this:
$(document).on('keyup', '#someDataTable', DoCalculations);
The function it invokes looks like this:
function DoCalculations() {
$(this).find('tr').each(function () {
var tUnits = $(this).find('.units').val();
var tValue = $(this).find('.value').val();
$(this).find('.autoTotal').val(Math.round(tUnits * tValue));
});
}
--
Now, my problem: I need to be able to rip out the commas to do the calculations. I was hoping to be able to use NumberFormatter's parseNumber() function to do this, but it was having a small fit. This was the alternate code in DoCalculations to attempt to accomplish that:
function DoCalculations() {
$(this).find('tr').each(function () {
var tTotal;
var tUnits = $(this).find('.units').val();
var tValue = $(this).find('.value').val();
tUnits = $.parseNumber(tUnits, { format: "#,###", locale: "us" });
tValue = $.parseNumber(tValue, { format: "#,###", locale: "us" });
tTotal = tUnits * tValue;
tTotal = $.formatNumber(tTotal, { format: "#,###", locale: "us" });
$(this).find('.autoTotal').val(tTotal);
});
}
But it comes back with a runtime error in NumberFormatter.js, where it cannot get the property of numberString.indexOf of undefined or null reference. Line 442 to be exact. I'm not sure why though. I originally thought it was because there were empty input boxes, but that turned out to not matter.
At the end of the day, I need to strip out commas.
Removing characters is something that regular expressions excel at:
var tValue = parseFloat($(this).find('.value').val().replace(/,/g, ''));
UPDATE
If val() can be null/undefined, you can add a check like this:
var tValue = $(this).find('.value').val();
tValue = tValue ? parseFloat(tValue.replace(/,/g, '')) : 0;

ParseFloat goes NaN

Hello everyone i have this code
function computeChange(){
var change;
var amountDue = parseFloat(document.getElementById("amountDue").value);
var amountReceive = parseFloat(document.getElementById("amountReceive").value);
change = amountReceive - amountDue;
document.getElementById('amountChange').innerHTML = change;
}
<td>Total Amount</td>
<td>Php:<span id="amountDue"><?php echo $sum; ?></span></td>
</tr>
<tr>
<td>Amount Paid</td>
<td><input type="number" id="amountReceive" required="required" maxlength="4" size="4" onKeyUp="computeChange()"></td>
</tr>
<tr>
<td>Change</td>
<td>Php:<span id="amountChange"></span></td>
</tr>
on the total amount is a decimal
on the amount paid input type=text
So the problem is if i enter something in the text box the span on change goes NaN
parseFloat( document.getElementById("amountDue").value );
is technically equivalent to
parseFloat( undefined );
which yields the value NaN because span elements do not have a property named .value. Maybe you wanted .innerHTML?
parseFloat( document.getElementById("amountDue").innerHTML );
#amountDue is a <span> element, so it does not have a value property.
Use .innerHTML to get its contents.
var amountDue = parseFloat(document.getElementById("amountDue").innerHTML);
This will not return you the value:
document.getElementById("amountDue").value
as amountDue is not a HTML input element.
Try below:
document.getElementById("amountDue").innerHTML;
i.e.
var amountDue = parseFloat(document.getElementById("amountDue").innerHTML);
value of amountDue is returning undefined, causing the parseFloat to return NaN
Use innerHTML instead. Change this row
var amountDue = parseFloat(document.getElementById("amountDue").value);
to
var amountDue = parseFloat(document.getElementById("amountDue").innerHTML);

Counting elements doesn't work

I have a table and want to calculate each element like:
calc-this-cost * calc-this-cost(value of checkbox) = calc-this-total
Then summ all calc-this-cost and put it to totalcost div.
This is table:
<td class="params2">
<table id="calc-params">
<tr>
<td>aaa</td><td class="calc-this-cost">159964</td><td class="calc-this-count">
<input type="checkbox" name="a002" value="0" onclick="calculate(this);" />
</td><td class="calc-this-total">0</td>
</tr>
<tr>
<td>bbb</td><td class="calc-this-cost">230073</td><td class="calc-this-count">
<input type="checkbox" name="a003" value="0" onclick="calculate(this);" />
</td><td class="calc-this-total">0</td>
</tr>
<tr>
<td>ccc</td><td class="calc-this-cost">159964</td><td class="calc-this-count">
<input type="checkbox" name="a004" value="1" onclick="calculate(this);" />
</td><td class="calc-this-total">0</td>
</tr>
........
</table>
.......
</td>
<div id="calc-total-price">TOTAL COST: <span>0</span></div>
My script (in function calculate)
var totalcost=0;
$('.params2 tr').each(function(){
var count=parseFloat($('input[type=checkbox]',$(this)).attr('value'));
var price=parseFloat($('.calc-this-cost',$(this)).text().replace(" ",""));
$('.calc-this-total',$(this)).html(count*price);
totalcost+=parseFloat($('.calc-this-cost',$(this)).text());
});
$('#calc-total-price span').html(totalcost);
Counting each element and put result to calc-this-cost - work perfect.
But totalcost result NaN. Why?
[general] don't parseFloat() more than you need to
[general] move repeating code to functions
[jQuery] use .find() over context and cache nodes ($row)
[general] look at how String.replace() works
[general] look at Number.toFixed() for displaying floats
example
var totalcost = 0,
toFloat = function(value) {
// remove all whitespace
// note that replace(" ", '') only replaces the first _space_ found!
value = (value + "").replace(/\s+/g, '');
value = parseFloat(value || "0", 10);
return !isNaN(value) ? value : 0;
};
$('.params2 tr').each( function() {
var $row = $(this),
count = toFloat($row.find('.calc-this-count input').val()),
price = toFloat($row.find('.calc-this-cost').text()),
total = count * price;
$row.find('calc-this-total').text(total.toFixed(2));
totalcost += total;
});
$('#calc-total-price span').text(totalcost.toFixed(2));
console.log() will solve all your problems:
$('.params2 tr').each(function(){
var count=parseFloat($('input[type=checkbox]',$(this)).attr('value'));
var price=parseFloat($('.calc-this-cost',$(this)).text().replace(" ",""));
$('.calc-this-total',$(this)).html(count*price);
totalcost+=parseFloat($('.calc-this-cost',$(this)).text());
console.log(count, price, totalcost)
});
Add more logging where every you don't understand something. Didn't I just tell you to use logging? :)

Categories

Resources