3

I'm trying to get the value of a specific html input that is named like:

<input type="hidden" value="." id="grid[0][0]">

where [0][0] could be any value within a foreach loop.

using Jquery:

var currVal = $('#grid['+x+']['+y+']').html();

I'm getting an undefined value. Not sure whether it's a syntax problem. I haven't found a similar example so I'd appreciate any help on this. Thanks!

Juan M
  • 4,063
  • 4
  • 19
  • 28
  • I...don't have a solution to this specific problem. I will *only* say that in 99% of cases, if you have an `id` with a number in it, you are doing it wrong. – Katana314 Jan 31 '16 at 17:17

2 Answers2

4

It actually is a syntax problem. jQuery interprets "#grid[...]" as an HTML element with the ID "grid" and some attribute (or other meta stuff) just like CSS would.

To solve simply escape the [ and ], like this:

$('#grid\\[' + x + '\\]\\[' + y + '\\]').val()

That should do it :)

Edit: As noted by Josh Crozier, the html() method is supposed to be used in normal tags (like div). For input, select or textarea you should use val() -- Docs on that: http://api.jquery.com/val/

Rafael Lins
  • 458
  • 7
  • 12
  • 1
    Yep, that would work. But it's also worth pointing out that [bracket characters are invalid in an ID attribute](http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html)... also, the OP is using the `.html()` method... it should be `.val()` since an `input` element can't contain HTML.. – Josh Crozier Jan 31 '16 at 17:03
  • Yeah, good you remembered that! Thanks! Totally forgot about the html()/val() thing (been ages since I used jQuery myself). Weird thing is that those IDs do work (albeit not recommended) – Rafael Lins Jan 31 '16 at 17:07
  • Thanks a lot, did not know about the brackets either, will remove that from the html ID :D – Juan M Jan 31 '16 at 17:13
  • @JoshCrozier no more with HTML5 the id could contain special characters...https://mathiasbynens.be/notes/html5-id-class – Zakaria Acharki Jan 31 '16 at 17:27
0

You can also do :

var currVal = $('input[id="grid['+x+']['+y+']"]').val();
smdsgn
  • 1,736
  • 1
  • 11
  • 11