Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery get element by id, multidimensional array

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!

like image 554
Juan M Avatar asked Jun 08 '26 18:06

Juan M


1 Answers

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/

like image 99
Rafael Lins Avatar answered Jun 10 '26 08:06

Rafael Lins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!