Change count down to count up - javascript

This script counts down from 60 to 0 and stops when it reaches 0.
<script type="text/javascript">
var counttx= "60";
var counterrx=setInterval(timerrx, 1000); //1000 will run it every 1 second
function timerrx()
{
counttx=counttx-1;
if (counttx < 0)
{
clearInterval(counterrx);
return;
}
document.getElementById("timerrx").innerHTML=counttx; // watch for spelling
}
</script>
Instead of counting down, I want the script to count up. I changed the - to a + in counttx=counttx-1; but then the following happend:
60
601
6011
60111
etc.

Looks like counttx is a string, and javascript is appending '1'. Try:
counttx = +counttx + 1;
Edit: or just remove the quotes in the var statement:
var counttx = 60;

If one operand of - operator is string and another is number JS converts the string to number. Thats why count down is working even if counttx is string. But when one operand of + is string and another is number JS converts the number to string and does a string concatenation. Thus you are getting 601, 6011 etc. instead of count up. To fix this you can declare counttx as integer.
var counttx = 60;

Remove the quotes from var countxx="60";
Write it as
var countxx=60;
and then change it to
counttx=counttx+1;
When you mention the value within quotes, it considers it as string and just appends 1 to the value, that is the reason your getting 601, 6011 etc.

You need to parse var to integer first then increment it. Use counttx = parseInt(counttx) + 1;

Do you want to count from 0 to 60? If so swap the 60 and the 0 in your script and change this line counttx = counttx + 1; to counttx = counttx - 1. Also get rid of the double quotes around 60.

Related

JQuery not showing correct decimal output

My problem with this is, everything is fine up to two decimal places when its preceded 1-9, however if the number is a 10th, then my script will only show to one decimal place.
E.g 200.19, 5000.42, 12.98 << will be fine however if the output should be 123.10 it will display 123.1
Here's my code:
jQuery(document).ready(function() {
function ReplaceNumberWithCommas(yourNumber) {
//Seperates the components of the number
var n= yourNumber.toString().split(".");
//Comma-fies the first part
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return n.join(".");
}
function loanCalc() {
//Get the parameter from the form
var rate=jQuery('#start_rate').val();
var priceValue=jQuery('#input_1_2').val();
console.log("price value before"+priceValue);
if(priceValue.indexOf('£') == 0) {
var strEnd=jQuery('#input_1_2').val().indexOf(',') - 1;
priceValue=parseInt(priceValue.substr(1,priceValue.strEnd))*1000;
}else{
priceValue=priceValue;
}
var princ = parseInt(priceValue);
var term = parseInt(jQuery('#input_1_3').val());
var intr = rate / 1200;
console.log("price"+priceValue+" term"+term+" rate"+rate);
var calculation = princ * intr / (1 - (Math.pow(1/(1 + intr), term)));
console.log("paymenet"+calculation);
var rePayment= calculation*term;
var costOfCredit=princ-rePayment;
//set the value
jQuery('#figure').html('£'+ ReplaceNumberWithCommas(calculation.toFixed(2)));
jQuery('#rate').html(rate+"%");
jQuery('#total').html('£' +
ReplaceNumberWithCommas(rePayment.toFixed(2)));
jQuery('#credit').html('£' + ReplaceNumberWithCommas(
Math.abs(costOfCredit.toFixed(2 ))));
As you can probably guess, there are 3 fields that I am displaying, the calculation, which is a percentage, 'rePayment' and 'costOfCredit'. The weird thing is 'rePayment' works fine and has no problem showing the 2nd decimal place even if its a 10th/ends with zero.
So my question is can you guys help me find what my problem is with getting the 2nd decimal place to show is?
When you call Math.abs(), it's converting the string with 2 digits after the decimal back to a number, which loses the trailing zeroes. You should call Math.abs() first, then call toFixed() on this to add the trailing zeroes.
jQuery('#credit').html('£' +
ReplaceNumberWithCommas(Math.abs(costOfCredit).toFixed(2)));

Convert string to hex then back to string

I have to convert a working C# function to JavaScript so it executes client-side. Here's the C#...
// convert the cmac into a hex number so we can increment it and get the emac
long emacLong = Convert.ToInt64(_cmac, 16) + 1;
emac = emacLong.ToString("x12").ToUpper();
Here's what I have so far in JavaScript..
var emac = parseInt(cmac, 16) + 1;
emac = emac.toString(16);
The input is "0015D1833339". The output should be "0015D183333A". However, the JavaScript returns "15d183333a". I need to retain the leading 0's. Looks like the C# function accomplishes this with the "x12" parameter of .ToString. How do I accomplish this in JavaScript? I need to convert it to an integer, increment it by 1 and then convert back to a string with a length of 12 characters.
Easy way to pad hex number output when you know the exact length you desire is with something like this:
var emac = parseInt(cmac, 16) + 1;
emac = ("000000000000" + emac.toString(16)).substr(-12);
// or if you MUST have all caps....
emac = ("000000000000" + emac.toString(16)).substr(-12).toUpperCase();
This example is for length 12, if you need a different length, you would adjust the length of the 0 string and the substr param.

Why is this not a clear integer type and how to make it clear?

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

Increase value of digit within HTML string (jQuery)

I have a bunch of images in a folder which are all named as numbers. The first one is displayed on document load.
<img src="image/01.jpg" />
I want to use jQuery to flick through the images. In other words, I want to convert the HTML to a string and then increase the value of what is currently "01".
So far I have:
$(document).ready(function(){
$("button").click(function(){
var $n = $("img").html(htmlString(17));
$n.val(Number($n.val())+1);
});
});
The bit that I'm sure I'm completely wrong on is the selecting of the digit (i.e delcaring var $n. I've tried to convert the HTML to a string there and count along the characters but I'm not even sure if that's the right route to be taking; I can't find anything similar anywhere.
Thanks.
img element doesn't have html content, apart from that you are using html as setter not getter. You can replace the src attribute's value using replace method:
$('img').prop('src', function(_, src) {
return src.replace(/\d+/, function(n) {
var num = +n + 1;
return num.toString().length === 1 ? '0' + num.toString() : num;
});
});
http://jsfiddle.net/Bb84Q/
You can just
1)catch the src value in a js variable
2) using substr function get rid of the "image/" part.
3) Then using split() on "." take the first array slot's value.
4)Convert that to integer using intVal() and
5) then increment the value
var source = "image/01.jpg";
var number = source.split(".")[0].split("/")[1];
number = (number *1) + 1
var newsource = "image/" + number + ".jpg";
this is how you'd actually get source
var source = $("img").attr('src');
just realized that this will make "image/2.jpg" , you could use a data-number attribute, you could re-name the images that are 1 - 9 , but this gives you an idea

How to get numeric value inside <td>

Trying to calculate sum of checked tr's.
var totalqt=0;
totalqt=totalqt + $(this).closest("tr").find("#qt").text();
It gets correct values but doesn't operate with it like digits. for ex, if value was 1 for first td, and 2 for second td, it alerts 12 instead of 1+2. Tried text() and html(). Same result. What's wrong?
totalqt = totalqt + parseInt($(this).closest("tr").find("#qt").text(), 10);
You need to parse the value as a number this will either be using parseInt(val, base) or parseFloat(val, base):
In your example you'd use:
var totalqt=0;
totalqt=totalqt +parseInt( $(this).closest("tr").find("#qt").text(), 10);
You need to parse the string to an int so that you can use it like an int.
var totalqt=0;
totalqt=totalqt + parseInt($(this).closest("tr").find("#qt").text(), 10);
The 10 is because:
The problem is with how parseInt guesses the base of your number. Read
the parseInt spec. Instead of always defaulting to base 10, it tries
to guess, and if the first character is '0' it thinks you want to
parse as an octal number, and if it starts with '0x' it thinks you
want hexadecimal.
text() returns a string. You want a number. Use parseInt:
var totalqt = 0;
totalqt = totalqt + parseInt($(this).closest("tr").find("#qt").text(), 10);

Categories

Resources