String format in javascript - javascript

I'd like to format a number and remove starting 0s from it. e.g.:
001 => 1
10 => 10
Actually, I have a jQuery method which does the following:
$('#myelement').text($('#myElement').text()+1);
When the element's text is 0, the function makes it 01, How can I make it to show 1 using jQuery or javascript?
Thanks.

what you need:
parseInt($('#myElement').text(), 10) + 1;
what you're asking for:
($('#myElement').text()+1).replace(/^0+/, '');

You can use parseInt("0010", 10).toString(). Ignore toString() if you need the int only.

Assuming you want to increment the value, convert the current text in to a number using unary +:
$('#myelement').text(function(i, v){
return +v + 1;
});

+"0001" //1
See above! .......

$('#myelement').text(parseInt($('#myElement').text(), 10) + 1);

Related

javascript format date from DDMMYYYY to DD/MM/YYYY

I have a datepicker and I want to parse the date to dd/mm/yyyy when user input is ddmmyyyy.
Image
I have add a javascript function to the input text but I don't know if I am on the right way
<inputText id="input1" onchange="parseDate()"/>
<script type="text/javascript">
$(document).ready(function() {
$("#input1").datepicker()
};
function parseDate() {
???
}
<script>
Thanks
If that's the exact format you're looking at, then you could just parse it out:
http://jsfiddle.net/q3yrtu0z/
$('#input1').change(function() {
$(this).val($(this).val().replace(/^(\d{2})(\d{2})(\d{4})$/, '$1/$2/$3'));
});
This is designed such that if the value is exactly 8 digits, then it will format it XX/XX/XXXX.
You may want to do additional validation on the validity of the date format (although you'd have to do this for MM/DD/YYYY inputs as well anyway)
Try this....
function convertDate(inputFormat) {function pad(s) { return (s < 10) ? '0' + s : s; } var d = new Date(inputFormat); return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/'); }
As you're going for a simple transformation, consider sliceing your String to the points where you want to add your characters, for example
var strA = '13102015',
strB = strA.slice(0, 2) + '/' + strA.slice(2, 4) + '/' + strA.slice(4);
strB; // "13/10/2015"
As this may be invoked multiple times if the user modifies it later, you may also wish to force the input into expected formatting at the start using replace, e.g.
'13/102015'.replace(/[^\d]/g, ''); // "13102015"
// now continue to slice
In a RegExp,
[chars] means match these characters (in this case c, h, a, r, s)
[^chars] is the inverse of [chars], i.e. match any character except these characters
\d is any digit, i.e. the numbers 0 to 9
The g flag means global, i.e. after a match keep looking for another match

Adding variable to a number in jquery id name

loopVar=1;
alert('#imgAvatar'+parseInt(loopVar)+1);
gives me #imgAvatar11
While
alert(parseInt(loopVar)+1);
gives me 2
How can I get #imgAvatar2 ?
Your loopVar is already an integer (notice you haven't put it in quotes, so it is integer). No need to do parseInt.
Use it:
loopVar=1;
alert('#imgAvatar'+(loopVar+1));
FIDDLE:
http://jsfiddle.net/15bucsy5/
It's because you're adding to the string #imgAvatar so the numbers will be converted to strings as well, and it's really read as "#imgAvatar" + "1" + "1".
Use parentheses to create a block where the numbers can be added up before they are added to the string
var loopVar = 1;
alert( '#imgAvatar' + ( (+loopVar) + 1 ) );
Whenever the addition operator is used with a string, all other values will be converted to strings as well
FIDDLE
Thats the trouble:
"foo" + 1 + 1 == "foo1"+1 == "foo11";
Thats the answer
alert( '#imgAvatar' + ( parseInt(loopVar) + 1) ) );
P.S. jsfiddle: https://jsfiddle.net/emtLfv9r/
If not worknig - show to us your html.
You need to add parenthesis () for priority to evaluate add loopVar first. If your variable contains numeric value then do not need to apply parseInt function.
loopVar = "1";
alert('#imgAvatar'+(parseInt(loopVar)+1));
OR
loopVar = 1;
alert('#imgAvatar'+ (loopVar+1) );
Demo

How to add one to a variable to make 2 not 11

Currently this makes 11. It's for a slideshow and the var "n" equals 1 by default
function forward() {
document.getElementsByClassName("img")[0].setAttribute("class","imgout");
setTimeout( function() {
var n1 = document.getElementById("img").getAttribute("data-number");
var n=n1+1;
document.getElementById("img").setAttribute("data-number", n);
document.getElementById("img").setAttribute("src", "images/" + n + ".jpg");
document.getElementsByClassName("imgout")[0].setAttribute("class","img");
}, 500)
}
Use parseInt():
var n = parseInt(n1, 10) + 1;
Instead of:
var n=n1+1;
When n1 will be a string, because it came from the DOM, you need to convert n1 to an integer. There are many ways to do this, and really you should probably use a regular expression to validate that n1 contains what you expect first, but that being said you can try any of the following:
var n=parseInt(n1, 10)+1;
var n=(n1*1)+1;
var n=(+n1)+1;
As an aside the regex for validating the input from the DOM might be something such as:
/^-?\d+$/
Use Number():
var n = Number("1");
FIDDLE
parseInt - good choice. Also you can do
var n = n-0+1
Just remember that of you have different types "+" will convert to string and "-" will convert to numbers
Convert n1 to number as it is a string like ~~n1. The ~~n1 form is good if you know you want an integer (a 32-bit integer).
Second way is to use Number() function i.e. Number(n1) will convert n1 value into a string.
var n=parseInt(n)+1;
Documentation
Fiddle

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

jquery , ajax data sum cant get to work correctly

$.post('ajax_ceneizbaze.php', function(cenovnik){
if(cenovnik){
cenastr=cenovnik.cenastrana;
cenadinamika=cenovnik.cenadinamika;
cenabaza=cenovnik.cenabaza;
cenakorpa = cenovnik.cenakorpa;
cenacms = cenovnik.cenacms;
inkrementodrzavanje = cenovnik.cenaodrzavanje;
rezz = parseInt(cenastr+cenadinamika);
alert(rezz);
}
else alert('bla bla..');
},'json');
initial value for cenastr is 25, and for cenadinamika is 50 ,Ajax works perfectly in this mine example, but when i try to sum values cenastr and cenadinamika i get output 2550 , instead 75? why i cant convert that to integer and to get sum of thoose two. it only output result in string format. i tried parseInt to place before sum operation but it doesnt helps.
you have to parseInt each of the strings:
rezz = parseInt(cenastr) + parseInt(cenadinamika);
Try that out
http://www.javascripter.net/faq/convert2.htm - this might help. You need to convert the strings to numbers before the calculation!
The + operator has a dual purpose. On strings it concatenates them:
"25" + "50" = "2550"
With numbers, it sums them.
25 + 50 = 75
Therefore we can deduce that your two variables are strings, and that you parse the result of concatenating them to an integer, giving you 2550.
You need to parse each individual value to an int before using the + operator to add them:
rezz = parseInt(cenastr,10) + parseInt(cenadinamika,10);
Make sure the variable are numbers before adding:
cenastr= +cenovnik.cenastrana;
cenadinamika= +cenovnik.cenadinamika;
//...
rezz = cenastr + cenadinamika;
parseInt will be working on the result of the addition, which, both being strings, will be the concatenation.
Either:
parseInt(cenastr) + parseInt(cenadinamika)
or use the unary operator:
(+censtr) + (+cenadinamika);

Categories

Resources