Henry C
Henry C

Reputation: 59

Why am I unable to get the value of this input field using jQuery?

I've been trying to figure out what's wrong with my code for a while now, and why it won't let me get the value of my input field.

My code looks like this:

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<input type=text id="0.1.2_00_1" value=0>
<script>
  console.log($('#0.1.2_00_1').val())
</script>

Why doesn't this work? Hopefully I'm not just being really dumb.

Upvotes: 0

Views: 89

Answers (3)

Scott Marcus
Scott Marcus

Reputation: 65796

The id contains the . character which, when passed to a JQuery selector, is interpreted as a CSS class qualifier.

It's causing JQuery to look for an element who's id is 0 that uses a CSS class of 1 and another called 2_00_1.

The official spec. says:

"Using characters except ASCII letters, digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility."

It's better to avoid them, if possible and use just alpha-numeric values for ids.

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<input type=text  id="x" value=0>
<script>console.log($('#x').val())</script>

Upvotes: 1

Travis Acton
Travis Acton

Reputation: 4440

If an ID carries a period (special character) in jquery you must escape it like so with double slashes:

console.log($('#0\\.1\\.2_00_1').val());

Upvotes: 4

j08691
j08691

Reputation: 207900

You need to escape the periods. For example $('#0\\.1\\.2_00_1')

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<input type=text id="0.1.2_00_1" value=0>
<script>
  console.log($('#0\\.1\\.2_00_1').val())
</script>

As the jQuery docs on selectors state:

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\.

Upvotes: 3

Related Questions