gtilflm gtilflm - 3 months ago 16
Javascript Question

Using javascript variable in jquery selector

I have a

<form>
with this input...

Term ID: <input type="text" name="data_array[0][term_id]" size="5" value="' . $highest_term_id . '">


where
$highest_term_id
is set by PHP.

I'm trying to use jquery to increment the "data_array[0]" part by...

$("input[data_array[" + index + "][term_id]").val((index + 1));


but I get this error:


Error: Syntax error, unrecognized expression:
input[data_array[undefined][term_id]"


A bit higher in the script I have
var index = 0;
;

Any ideas why this is failing?

Answer

The square bracket has special meaning in jQuery selectors - you'll have to escape them - should be something like:

$("input[name=data_array\\[" + index + "\\]\\[term_id\\]]").val((index + 1));

I'd try to avoid this naming convention if possible, or try to find an alternative to selecting it by name - as you can see, it's hard to keep the brackets and backslashes straight when referencing it.

Comments