107

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.

6
  • 11
    Just the way you've done it. But if you want to be explicit, you can change id to id.toString(). Commented Nov 20, 2010 at 19:28
  • 4
    Yes, you've done it correctly. If it's "not working", then something else is wrong, like there isn't actually an element with that ID. Commented Nov 20, 2010 at 19:29
  • 1
    This code: getElementById("horseThumb_{$id}") is not JavaScript, it's PHP. So that's why it didn't work for you. Commented Nov 20, 2010 at 19:30
  • 1
    Your syntax is right, but check the case of the element, remember Javascript is case-sensitive. Some browsers will let you find an element case-insensitive, but not all browsers do that Commented Nov 20, 2010 at 19:31
  • 1
    @Cory That should never be needed. The id argument is concatenated to a string, ergo, it will be coerced to the String type. Another case would be if you would not know what the type of the other operator is - but in this case it is s string literal, so casting is not required. Commented Nov 20, 2010 at 19:37

5 Answers 5

87

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.

Since ECMAScript 2015, you can also use template literals (aka template strings):

document.getElementById(`horseThumb_${id}`).className = "hand positionLeft";

To identify the first case or determine the cause of the second case, add these as the first lines inside the function:

alert('ID number: ' + id);
alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));

That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById. If you get undefined 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 get null 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:

<head>
<title>My Web Page</title>
<script>
    function AddBorder(id) {
        ...
    }
    AddBorder(42);    // Won't work; the page hasn't completely loaded yet!
</script>
</head>

To fix this, put all the code that uses AddBorder inside an onload event handler:

// Can only have one of these per page
window.onload = function() {
    ...
    AddBorder(42);
    ...
} 

// Or can have any number of these on a page
function doWhatever() {
   ...
   AddBorder(42);
   ...
}

if(window.addEventListener) window.addEventListener('load', doWhatever, false);
else window.attachEvent('onload', doWhatever);
Sign up to request clarification or add additional context in comments.

1 Comment

It will not work for some embedded JavaScript Engines - such as mJS - will lead to the error like MJS callback error: implicit type conversion is prohibited. For that case required to use explicit type conversion
40

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:

1+2+3 == 6
"1"+2+3 == "123"

4 Comments

And just for fun what's the result of: 2 + "3" - 5? (no cheating)
Or, even better, the result of: 4+"5"-3?
too late to answer but ... 2 + "3" will gives "23" (by concatenation) and "23" - 5 will gives you 18 (subtraction make a parse to string) You can test it in you console ...
Never forget that the operators are evaluated from left to right, so: 1+2+'3'+4+5 // 3345
4

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:

var str = 'horseThumb_'+id;

str = str.replace(/^\s+|\s+$/g,"");

function AddBorder(id){

    document.getElementById(str).className='hand positionLeft'

}

Comments

1

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.

Comments

0

Another way to do it simpler using jquery.

sample:

function add(product_id){

    // the code to add the product
    //updating the div, here I just change the text inside the div. 
    //You can do anything with jquery, like change style, border etc.
    $("#added_"+product_id).html('the product was added to list');

}

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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.