1

Suppose I have a form with input element naming scheme that is a multidimensional array. Such as:

<form>
    <input type="number" name="foo[123][456][789]" />
</form>

Is it possible to use jQuery (CSS selectors) to select all inputs where the name starts with foo, and has a specific value in the second array selector?

For example, the following is a possible valid selection (second array selector is always 456):

<input type="number" name="foo[123][456][1]" />
<input type="number" name="foo[422][456][2]" />
<input type="number" name="foo[443][456][3]" />
<input type="number" name="foo[211][456][4]" />
  • 1
    Not a single selector but I am pretty sure you can use a function and select the ones you need. Getting the foo start is really easy, you just have to sort out the stuff after it – Huangism Aug 01 '19 at 17:22
  • 2
    You can use `input[name^='foo[']` to match names that start with `foo[`. Use `.filter()` with a function of your own that looks for `456`. – Barmar Aug 01 '19 at 17:24
  • There are also third-party add-ons that implement regular expression attribute selection. You could use that. – Barmar Aug 01 '19 at 17:25
  • See https://stackoverflow.com/questions/190253/jquery-selector-regular-expressions – Barmar Aug 01 '19 at 17:25
  • Looks like I am wrong about the single selector, `input[name^="foo["][name*="][456]["] ` https://jsfiddle.net/cph8defg/ – Huangism Aug 01 '19 at 17:43

1 Answers1

0

Use attribute selectors. ^= is for selecting on attribute values that begin with the specified string. *= is for selecting on attribute values that contain the specified string. Quoting included so the brackets don't confuse the selector.

$('input[name^="foo["][name*="][456]["]')

In English: Select input elements that have an attribute called name whose value begins with foo[ and have an attribute called name whose value contains ][456][.

Ouroborus
  • 16,237
  • 4
  • 39
  • 62