This code doesn't seem to understand the integer in the var.
var btndelivery = $j('.delivery').parent("li");
var grandtotaltxt = $j(".gtman").text().replace("$", "");
var grandtotal = parseInt(grandtotaltxt);
alert(grandtotal);
$j(document).ready(function() {
if ($j(grandtotal) > 60) {
alert("plus grand");
$j(btndelivery).show();
} else {
alert("plus petit");
$j(btndelivery).hide();
}
})
It always alerts plus petit.
The variable grandtotal was already parsed into an integer. It looks like you need to remove the jQuery wrapping to compare it to another integer. Also, if $j(".gtman").text() comes back undefined then the replace function will throw an error. It's probably good to wrap the code in an if statement.
if ($j(".gtman").length) {
var btndelivery = $j('.delivery').parent("li");
var grandtotaltxt = $j(".gtman").text().replace("$", "");
var grandtotal = parseInt(grandtotaltxt);
alert(grandtotal);
$j(document).ready(function() {
if (grandtotal > 60) {
alert("plus grand");
$j(btndelivery).show();
} else {
alert("plus petit");
$j(btndelivery).hide();
}
});
}
You can use '+' sign infront of the variable you expect as integer.
like
var integerVal = +$('someSelector').text();
This makes integerVal variable an integer variable and you need not to put parseInt for it.
You can refer this article for more such JavaScript Tricks.
Related
I am calculating 2 fields on a form with values but it seems in some cases it's not working. Here's my javascript. I am adding $oneTimeCostField and $recurringTotalCostField to get the value into the $totalRetailAmountField. Here's the result I am getting when I add say 1,555.00 + 566.00 = the value is 567.00 (?). Any idea what I'm doing wrong? In some cases it works correctly when the values are lower. Thanks, just stumped
var $recurringCostField = $('#am_attribute_campaign_addon_monthly_cost_value');
var $recurringTotalCostField = $('#am_attribute_campaign_addon_total_monthly_cost_value');
var $totalRetailAmountField = $('#am_oie_string_total_monthly_cost_value');
var $oneTimeCostField = $('#am_attribute_campaign_addon_one_time_cost_value');
function calcVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
var result = parseFloat(num1) + parseFloat(num2);
if (!isNaN(result)) {
$totalRetailAmountField.val(result.toFixed(2));
}
}
calcVal();
$oneTimeCostField.on("keydown keyup", function() {
calcVal();
});
$recurringTotalCostField.on("keydown keyup", function() {
calcVal();
});
You need to remove the commas before parsing:
var result = parseFloat(num1.replace(/,/g, '')) + parseFloat(num2.replace(/,/g, ''));
similiar question on this link
Remove commas from the string using JavaScript
That is because parseFloat() converts the string "1,555.00" to the number 1.
To convert it to a proper floating point number, it needs to include a single dot only.
console.log(parseFloat("1.555"));
I have this code:
wallboard.data.Timer = function () {
$("div[data-value]").each(function () {
var time = $(this).attr("data-value");
if (time > 0) {
time += 1000;
$(this).attr("data-value", time).text(TimeToText(time));
}
});
}
The function TimeToText() simply takes a millisecond value and output it as hour:seconds (00:00).
The attribute data-value contains a millisecond value and is stores in the variable time.
This is my "debug" output:
var time = $(this).attr("data-value"); time = 4376
if (time > 0) { is true as 4376 is larger than 0
time += 1000; after this "time" is 43761000 - her it starts concatenating the text "4376" and "1000" and this is the proof that the JavaScript engine thinks time is a string type.
How do I make it clear that time should be an integer type?
var time = $(this).attr("data-value");
var timeInt = parseInt(time) + 1000;
You can use coercion trough the unary +, or just wrap it in a parseInt with a base of 10.
wallboard.data.Timer = function () {
$("div[data-value]").each(function () {
var time = parseInt($(this).attr("data-value"), 10);
if (time > 0) {
time += 1000;
$(this).attr("data-value", time).text(TimeToText(time));
}
});
}
Also, you could have searched for "javascript string to number" and you would find billions of results.
EDIT: Why not interpret numeric strings as numbers automatically? Because that would be a very unpleasant deviation from the convention: in JS you try to modify as little as possible your outputs. If you then wanted to actually concatenate two numeric strings together, you'd have to do lots of hacks to do it:
Instead of var a = "1000" + "10" to get "100010", you would have to do something like this
var a = ["1000", "zz10"].join(""); // note the "zz", so it's not plain numeric.
a = a.replace("zz", ""); // replace "zz" with nothing.
// now `a` would be "100010"
You need to convert the string retrieved with attr() into a number, e.g.
var time = +($(this).attr("data-value"));
You can use unary plus operator to convert the string attribute value to a number(you can also use parseInt())
var time = +$(this).attr("data-value");
You should convert the string to integer before adding it with 1000.
var time = parseInt($(this).attr("data-value"));
I'm trying to do a function for making a small calcul with vat.
So I have the following code:
<script type="text/javascript">
function calcdebours()
{
var taux = document.getElementById('debours_taux_tva').value;
var ht_no_tva = document.getElementById('debours_montant_ht_no_tva').value;
var ht_tva = document.getElementById('debours_montant_ht_tva').value;
var tva= Math.round((((ht_tva)*(taux))/100)*100)/100;
;
if(taux=='')
{
taux=0;
}
if(ht_no_tva=='')
{
ht_no_tva=0;
}
if(ht_tva=='')
{
ht_tva=0;
}
document.getElementById('debours_montant_tva').value = tva ;
document.getElementById('debours_montant_ttc').value = (tva) + parseInt(ht_tva)+ parseInt(ht_no_tva)
}
</script>
And below the fiddle:
http://jsfiddle.net/6zzRZ/
But for all it make the wrong calculation, I think it does not count the cent.
I've tried using just var 1 + var 2 but it just used to concatenate the number sor I use the parseInt function.
It has worked but the result is wrong for any kind of amount.
The trouble is that I tried parseDecimal but it say that this function does not exist.
Any kind of help will be much appreciated.
Try parseFloat. Or use the unitary + like this: var ht_no_tva = +document.getElementById('debours_montant_ht_no_tva').value; This gives JavaScript the hint that it should treat the value as a number.
Use parseFloat() instead of parseDouble:
http://www.w3schools.com/jsref/jsref_parsefloat.asp
In Javascript I have a number and I want to add comma to it when it's displayed as a string.
I can add comma to the number like this:
function numberWithCommas(value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
But I don't want to call a method on every number that we have to get this. I want to do something similar to this:
Number.prototype.toString = function(radix) {
return numberWithCommas(this);
}
So when I do the following, the right value will show up:
var num = 100000;
alert(num); // 100,000
Can't get the above to work. Any ideas?
What about creating a new number function?
Number.prototype.withCommas = function(){
return this.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
var n = 1234567;
alert( n.withCommas() );
http://jsfiddle.net/kyX8x/1/
I have a text box where the value is the result of a calculation carried out in jQuery. What I would like to do, using jQuery, is to display brackets around the number in the text box if the number is negative.
The number may be used again later so I would then have to remove the brackets so further calculations could be carried out.
Any ideas as to how I could implement this?
Thanks
Zaps
function FormatTextBox(id) {
var txtBox = $(id).val();
//strip bracket to get the number only
txtBox = txtBox.replace("[", "").replace("]", "");
var val = parseFloat(txtBox);
if (val < 0) {
txtBox.val("[" + val + "]");
} else {
txtBox.val(val);
}
return val;
}
First, store your calculation in a variable. You shouldn't be using the DOM to store data (in most cases). This basically eliminates your problem.
Number.prototype.bracketed = function() {
if(this < 0) {
return '[' + -this + ']';
} else {
return '' + this;
}
};
var result = do_calculation();
myTextBox.value = result.bracketed();
// result still holds the original Number value.
If you really want to store the data as the .value of the text input, you can make an unbracketed function as well:
String.prototype.unbracketed = function() {
var parts = this.match(/^\[([0-9]+)\]$|^([0-9]+)$/); // [number] or number
if(parts[1]) { // [number]
return -parseInt(parts[1], 10);
}
if(parts[2]) { // number
return parseInt(parts[2], 10);
}
return NaN;
};
Assuming you might have multiple fields (and you don't want the negative sign):
jQuery('input').each(function(){
if(jQuery(this).val() < 0 ){
jQuery(this).val('['+-1*jQuery(this).val()+']');
}
}
)
Then when you grab the value again, just strip the brackets and multiply by -1 to make it negative.
EDIT:
You can also use jQuery('input').data() to store the original number so you don't have to parse it again. (read more: http://api.jquery.com/data/ )