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*');
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.
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]">
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.