gtilflm gtilflm - 1 year ago 53
Javascript Question

Using javascript variable in jquery selector

I have a

with this input...

Term ID: <input type="text" name="data_array[0][term_id]" size="5" value="' . $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:

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

Any ideas why this is failing?

Answer Source

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.