Here’s a quick little tip to keep in mind when working with JavaScript: you can quickly convert a number (int, decimal, etc.) to a string by doing this
var i = 1;
var newString = i + "";
Edit on 11/21/06, 12:21PM Eastern. As pointed out in the comments below, my "excellent" example is totally bogus and leads to invalid (X)HTML. (It does, however, work in browsers, while it shouldn’t.) If you need a numeric ID, do what I do in the real world, not in my examples: preface it with a unique identifier. (Talking about baseball cards? How about using "bbc_NUMBER"?). In my own defense, this was the only thing I could think of to illustrate my point at the time. Bad example follows. ARGH!.
Now, you’re thinking: wow, why would you explain something so stupidly simple? Because even though it’s simple, it’s a useful and powerful technique. How? What if you’re working with numeric IDs on the backend that are printed dynamically into your code on the front end? Eventually, you’ll wind up with something like <element id="1" />. You’ll have a string ID and need to send an int back. Or, you’ll be iterating through a for loop, and you’ll need to do something with that iterator (access an element in the DOM, say).
Let’s say you have a function that looks like this bound to element’s onclick:
function myFunction(anID){
// hide clicked-on element
document.getElementById(?????).style.display = "none";
for(var i = 0; i<4; i++){
document.getElementById(?????).style.color = "red";
}
// send an AJAX request back with this ID
sendAjax(anID);
//Yellow fade to show done
yellowFade();
}
Is anID an int? Convert it to a string in your document.getElementById() call like so:
document.getElementById(anId+"").style.display = "none".
What about that for block? Fill that in like so:
document.getElementById(i+"").style.color = "red";
>Your ints are now strings.
technorati tags:javacript, dom, dhtml