Reputation: 576
I have a couple of input boxes that get dynamically created, and then filled. When I try and read these, I just get "undefined" as an answer. This pisses me off, because the same code works everywhere on other places on my web app. The code I use for grabbing the value looks like this:
$('#box1.1').val()
So this SHOULD return the value of element with id = "box1.1", am I right?
Firebug console:
>>> $('#box1.1').val()
undefined
And yes, I do use jQuery. Version 1.6.2.
Thanks in advance!
Upvotes: 0
Views: 154
Reputation: 76258
This is not a valid id (in jQuery's parlance at least): "box1.1". You cannot have a dot in the id as it'll confuse the jQuery selector engine since dot usually means a class name.
You can change the id to say: "box1_1" and try.
Here's a demo fiddle: http://jsfiddle.net/UnUYP/
Upvotes: 2
Reputation: 50523
No that is looking for an element with the id of "box1" with a class applied named "1"... In a jquery selector the # refers to an id selector (css selector) and the . refers to a class name. Best practice to avoid using periods for id values
Upvotes: 1
Reputation: 13716
In jQuery, the period has special meaning. They're used to prefix class selectors. There's no way for jQuery to know that .1 is part of the ID and not some CSS class named 1. You should instead use a character that doesn't have a special meaning, e.g. an underscore.
Upvotes: 1
Reputation: 82078
It is generally best to think of the $
function in jQuery as something which accepts a comma delineated list of CSS selectors. In CSS, the .
means, "object with the class name of..." Therefore, jQuery is looking for something under the box1 id which has the class of 1. Basically, in this example:
<div id="box1"><span class="1"></span></div>
jQuery would return the span. In this example:
<div id="box1.1"><span class="not_1"></span></div>
jQuery necessarily returns undefined
.
Because your ID causes conflicts in CSS, then your best bet is to simply remove the .
from the class names themselves. Normally an _
or a -
would be preferable.
Upvotes: 4
Reputation: 23585
You should escape the dot with two backslashes so jQuery doesn't treat .1
as a class.
$('#box1\\.1').val();
Upvotes: 4