http://jsfiddle.net/mretchin/JEVuX/40/
That’s my code. I’m trying to make an input box that takes a number, using the .val() method, and positions the red box with that value with the .css() method. I can’t figure it out…? As lame as this sounds, when I wrote it a few hours ago and debugged it in IE, it worked, but when I got home, the same jsfiddle link wasn’t functioning on Chrome. Is it just my browser? The code will accept 0 as an attribute, but not anything else.
Thanks for helping!
The problem is that
.val()returns a string. One way to solve this–as others here have noted–is by appendingpxto the end of the string. However, you can instead pass a true numeric value to the.css()method, in which case you don’t need to appendpx. I prefer this way of doing it, as it requires less code and leaves things more easily readable.All you need to do is add a plus sign before
$(this).val()in order to coerce it into a number:var value = +$(this).val()And then the rest of your code will work fine.
Beyond this specific case, not needing to append
pxis useful to know because you’ll often be grabbing CSS values using methods like.width(), which automatically return a number.