So I am trying to make a string out of a string and a passed variable(which is a number). How do I do that?
I have something like this:
function AddBorder(id){
document.getElementById('horseThumb_'+id).className='hand positionLeft'
}
So how do I get that 'horseThumb' and an id into one string?
I tried all the various options, I also googled and besides learning that I can insert a variable in string like this getElementById("horseThumb_{$id}")
<-- (didn't work for me, I don't know why) I found nothing useful. So any help would be very appreciated.
This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.
example:
In javascript the "+" operator is used to add numbers or to concatenate strings. if one of the operands is a string "+" concatenates, and if it is only numbers it adds them.
example:
It's just like you did. And I'll give you a small tip for these kind of silly things: just use the browser url box to try js syntax. for example, write this:
javascript:alert("test"+5)
and you have your answer. The problem in your code is probably that this element does not exist in your document... maybe it's inside a form or something. You can test this too by writing in the url:javascript:alert(document.horseThumb_5)
to check where your mistake is.Another way to do it simpler using jquery.
sample:
Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add.
Best Regards!
Your code is correct. Perhaps your problem is that you are not passing an ID to the
AddBorder
function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.To identify the first case or determine the cause of the second case, add these as the first lines inside the function:
That will open pop-up windows each time the function is called, with the value of
id
and the return value ofdocument.getElementById
. If you getundefined
for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but getnull
in the second.The third case would happen if your web page looks like this, trying to run
AddBorder
while the page is still loading:To fix this, put all the code that uses AddBorder inside an
onload
event handler: