Adding variable to a number in jquery id name - javascript

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

Related

Add together numbers in separate DIVs

(obligatory I'm new to this) What I am trying to do is...
Fetch the contents (a number) of the DIV ID.
Add those numbers together
Print them in the "at" DIV.
I know it should be pretty darn simple. But I cant wrap my head around why it isn't working. I want to learn WHY it's not working. I dont necessarily want you guys to write it for me. I want to learn. Here is my code...
var at = document.getElementById("a-total");
var ac = document.getElementById("a-coffee").innerHTML;
var ah = document.getElementById("a-hobby").innerHTML;
var af = document.getElementById("a-fundme").innerHTML;
var addopt = ac + ah + af;
function aTotal (){
if (addopt >= 0){
at.innerHTML = addopt;
} else {
console.log("tis broken");
}
}
aTotal();
It outputs properly, but it's just not adding the numbers in the DIVs together. It's placing them side by side rather than adding them together.
That's because you are only doing a string concatenation.
You need to transform the values to numbers as .innerHTML() returns a string. This is how should your operation:
var addopt = +ac + +ah + +af;
Note:
It's better to use .innetrText() or .textContent() over .innerHTML to avoid getting HTML markups inside your elements if there are any into the result.
This happens a lot. What you need to do is convert to integer because it reads it as a string using ParseInt (variable) or ParsefLoat (variable) ParsefLoat (variable) can also use .toFixed (decimal_places)
You have to parse the content of the divs to a number, as the innerHTML returns a string.
So either var addopt = +ac + +ah + +af; or var addopt = parseInt(ac) + parseInt(ah) + parseInt(af); should work for you.
You need to parse the innerHTML to integers or floats to be able to do mathematical operations on them. Check the below code that takes the text and parses it to ints:
var addopt = parseInt(ac) + parseInt(ah) + parseInt(af);
You try to additionnal strings instead of numbers.
innerHTML return the string in a HTML element.
You should parseInt or parseFloat the content to have numbers.
<script>
var at = document.getElementById("a-total");
var ac = document.getElementById("a-coffee").innerHTML;
var ah = document.getElementById("a-hobby").innerHTML;
var af = document.getElementById("a-fundme").innerHTML;
// Values are taken as string and mus be converted to int.
// We check also that a value is not undefined.
ac = isNaN(parseInt(ac)) ? 0 : parseInt(ac);
ah = isNaN(parseInt(ah)) ? 0 : parseInt(ah);
af = isNaN(parseInt(af)) ? 0 : parseInt(af);
var addopt = ac + ah + af;
function aTotal (){
if (addopt >= 0){
at.innerHTML = addopt;
} else {
console.log("tis broken");
}
}
aTotal();
</script>
The contents of your divs are strings, even though the represent numbers. So if your divs have the values '1', '2' and '3' adding them togther gives you '123' rather than 6 as you might expect. Have a look at the parseInt function to see how you can turn your strings into numbers.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Declare JavaScript variable only with ' ' marks

I saw one of the masters doing this:
var example = '';
Then later he continued with this:
example += '<div>just a div</div>';
I wanna know if there's any difference from doing this:
var example;
example += '<div>just a div</div>';
I don't really know if by doing the second method I'm doing wrong and I have to code like shown if the first example.
Updated!
Thank you so much for your answers, Ok I got it I need to define my variable to be able to work woth it, but then another question came... This master also is doing this:
var guess;
and then he does:
guess += myfunction( upper );
where myfunction was declared as follows:
function myFunction( upper ){
return Math.floor( Math.random() * upper ) + 1;
}
So, why here is different? Can any of you answer this please?
Thank you!
Second update!
Again Thanks!
I decided to post the whole code the JS master was doing, at this point I don't understand, so probably you'll be able to clear my doubts.
var randomNumber = myFunction( 10 );
var guess;
var attempts = 0;
var answer = false;
function myFunction( upper ){
return Math.floor( Math.random() * upper ) + 1;
}
do{
guess = prompt( "I created a number from 1 till 10, can you guess it?");
attempts += 1;
if( parseInt( guess ) === randomNumber ){
answer = true;
}
}while( ! answer )
document.write( "Took you " + attempts + " attempts to guess the number " + randomNumber);
Please have a look at:
var guess;
and how later is being declared, so why here works perfectly but in my first example I have to put the '' when declaring my variable?
I hope my question is clear enough for you!
Thank you for your time and patient!
When you do:
var example;
example += '<div>just a div</div>';
You end up with:
`"undefined<div>just a div</div>"`
This is because when you don't initialize a variable, it is undefined, which can be converted to a sensible string "undefined" when you try to add it to another string.
When you do:
var guess;
guess += myfunction( upper );
function myFunction( upper ){
return Math.floor( Math.random() * upper ) + 1;
}
You are adding a number to undefined. This results in NaN (not a number) because undefined cannot be converted into a sensible number.
You can check this yourself next time by opening up your browser's developer tools and running the code in the console.
Edit:
When you do:
var guess;
guess = prompt( "I created a number from 1 till 10, can you guess it?");
There's no issue because you are simply assigning a string to the guess variable. In the previous examples you were adding something to a variable, which means if they are different types then JavaScript has to try to do something sensible.
If you don't initialize your variable it has a value of undefined.
In your last example, you are really saying example = undefined + '<div>just a div</div>' and undefined will be converted to a string and output that way. Probably not what you want.
In general it is a good idea to initialize your variables before you use them which is why var example = '' is preferable in this case.
var myvar
myvar += 'asdf'
console.log(myvar) // prints undefinedasdf
var othervar = ''
othervar += 'sdfasdf'
console.log(othervar) // prints sdfasdf
If you don't initialize the variable then it will be undefined
Appending to undefined object doesn't help.
var example = '';
Here you are initializing an empty string to the variable and therefore appending a string to another string will give the desired output of string concatenation.
Output:
"undefined<div>just a div</div>"
"<div>just a div</div>"
Yes there is a difference the first snipet from the master creates a variable example and gives it a default value, the second statement concatinates the value with 'just a div'
.Your code has an error as it is adding a value to a non-existed value as variable example has no default 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);

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