1

html

<input name="single">

<input name="multi[]">
<input name="multi[]">

<input name="multi_keys[my]">
<input name="multi_keys[key]">

jQuery

var match_single      = $('[name="single"]');
var match_multi       = $('[name="multi"]'); // No match
var match_multi_keys  = $('[name="multi_keys"]'); // No match

console.log(match_single.length);
console.log(match_multi.length);
console.log(match_multi_keys.length);

It will only match match_single because the other selectors are not correct.

How can I make them match the form field arrays as well?

I could do this:

var match_multi       = $('[name="multi[]"]');

but how can I match when there are keys inside and they are unknown? I would like to write it like this:

$('[name="multi_keys*');
2
  • Don't match by attribute values, prefer class selectors. Commented Apr 12, 2017 at 13:03
  • @dfsq I'm working with a form where I don't have much control over the html output. I need to figure out some way with jQuery and the dom. Commented Apr 12, 2017 at 13:06

3 Answers 3

6

You can use ^= which matches what an attribute starts with:

$('[name^="multi"]')

Note that this will match both name="multi[]" and name="multi_keys[]". If you wish to select multi[] and multi_keys[] separately, you can simply add the opening square bracket to that selector:

$('[name^="multi["]')

...and:

$('[name^="multi_keys["]')

[att^=val]

Represents an element with the att attribute whose value begins with the prefix "val". If "val" is the empty string then the selector does not represent anything.

W3C's Selectors specification

Sign up to request clarification or add additional context in comments.

1 Comment

That's really brilliant! I'm really glad that you thought of that pitfall and a fix for it as well.
0

use the * before the = like this $('[name*="multi"]');

var match_single = $('[name="single"]');
var match_multi = $('[name*="multi"]'); // No match
var match_multi_keys = $('[name*="multi_keys"]'); // No match

console.log(match_single.length);
console.log(match_multi.length);
console.log(match_multi_keys.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="single">

<input name="multi[]">
<input name="multi[]">

<input name="multi_keys[my]">
<input name="multi_keys[key]">

Comments

0

You can query these inputs by matching the prefix of the input names, like $('[name^=multi_keys]') so it will pick up elements which' name starts with multi_keys . But it is quite hacky.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.