80

I've found similar questions here but nothing works for me.

have inputs like:

<input type="text" value="2" name="pages_title[1]">
<input type="text" value="1" name="pages_title[2]">

trying to get these fields like:

$('input[name="pages_title[]"]')

but have empty results :(

how to get all fields? I can only get it like $('input[name="pages_title[1]"]')

Rafael Herscovici
  • 16,558
  • 19
  • 65
  • 93
abiku
  • 2,236
  • 3
  • 25
  • 30
  • possible duplicate of [jQuery selector for inputs with square brackets in the name attribute](http://stackoverflow.com/questions/2364982/jquery-selector-for-inputs-with-square-brackets-in-the-name-attribute) – epascarello Oct 22 '13 at 22:26
  • 1
    Ah, misread question. Close vote is wrong...need to use starts with selector. – epascarello Oct 22 '13 at 22:28
  • @epascarello - how would begin with help to get all of them? – Rafael Herscovici Oct 22 '13 at 22:29
  • I made a simple plugin that will recursively generate a JSON object representation of these "multidimensional input fields": http://codepen.io/alexweissman/pen/MyWZdN – alexw Feb 28 '16 at 23:31

12 Answers12

117

Use the starts with selector

$('input[name^="pages_title"]').each(function() {
    alert($(this).val());
});

jsfiddle example

Note: In agreement with @epascarello that the better solution is to add a class to the elements and reference that class.

97ldave
  • 5,249
  • 4
  • 25
  • 39
37

const textValues = $.map($('input[type=text][name="pages_title[]"]'), function(el) { return el.value; });
   console.log(textValues);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="Hello" name="pages_title[]">
<input type="text" value="World" name="pages_title[]">
Rafael Herscovici
  • 16,558
  • 19
  • 65
  • 93
  • 3
    To iterate over each one, use `$('input[name="pages_title[]"]').each(function() { var aValue = $(this).val(); });` – Luke Shaheen Oct 22 '13 at 22:25
  • 1
    sorry but this will not work, as I described in my question. It will work only if i have fields names like pages_title[] but not pages_title[1] pages_title[2] pages_title[3] – abiku Oct 22 '13 at 22:27
  • 3
    @Dementic but that is fully legal to have that. You could have more dimensions name="page_tile[1][name]" and name="page_title[2][name]" so you need to support [1] etc – Dss Jan 23 '14 at 18:30
  • 2
    @Dss - it is legal, but the naming comes to represent an array, `[1]` would represent a different array then `[2]` – Rafael Herscovici Jan 24 '14 at 21:13
  • 3
    -1 It's not only legal, but it's an absolute must when I have a variable number of fields associated to the field-array, and no guarantee either of the order or inclusion of each one. I *have* to be able to supply unique ID's that I can count on once submitted. – oucil Feb 14 '15 at 22:20
26

use map method we can get input values that stored in array.

var values = $("input[name='pages_title[]']").map(function(){return $(this).val();}).get();
Muhammad Hassaan
  • 7,296
  • 6
  • 30
  • 50
user3021515
  • 261
  • 3
  • 7
13

You need to use the starts with selector

var elems = $( "[name^='pages_title']" );

But a better solution is to add a class to the elements and reference the class. The reason it is a faster look up.

epascarello
  • 204,599
  • 20
  • 195
  • 236
  • and then what happens in the case of `name="pages_titles"` ? also, why use a class, when its clear the `name` should be the same? extra markup for fun? – Rafael Herscovici Oct 22 '13 at 22:33
  • 2
    No it is not fun... because the `^=` is a lot slower than a class selector. It has to parse strings and check for a match. And I have no idea what you mean with the `name="pages_titles"` – epascarello Oct 22 '13 at 22:40
  • 1
    as per your answer, starts with, will also catch `pages_titles` (instead of `pages_title`). i agree that he should narrow down he's selector to something like `#divId[name='pages_title']` but why adding a class? the difference would be so little, it wont be noticed. – Rafael Herscovici Oct 22 '13 at 22:42
  • one more thing (sorry for picking..) since ajax was not mentioned, this form might be submitted regularly, and as for your `add class` solution, he will get no results at the server side. – Rafael Herscovici Oct 22 '13 at 22:49
  • 1
    This answer is interesting and even with deeper thoughts about regex parse consuming, for plug-in, for example, it would be better choice to go with classes - much faster, agree with epascarello. – Arthur Kushman Jun 14 '15 at 07:35
13

Put the input name between single quotes so that the brackets [] are treated as a string

var multi_members="";
$("input[name='bayi[]']:checked:enabled").each(function() {
    multi_members=$(this).val()+","+multi_members;
});
bmatovu
  • 3,756
  • 1
  • 35
  • 37
Limitless isa
  • 3,689
  • 36
  • 28
9

You can give your input textboxes class names, like so:

<input type="text" value="2" name="pages_title[1]" class="pages_title">
<input type="text" value="1" name="pages_title[2]" class="pages_title">

and iterate like so:

$('input.pages_title').each(function() {
    alert($(this).val()); 
});
Gregory R.
  • 1,815
  • 1
  • 20
  • 32
7

I think the best way, is to use a Propper Form and to use jQuery.serializeArray.

<!-- a form with any type of input -->
<form class="a-form">
    <select name="field[something]">...</select>
    <input type="checkbox" name="field[somethingelse]" ... />
    <input type="radio" name="field[somethingelse2]" ... />
    <input type="text" name="field[somethingelse3]" ... />
</form>

<!-- sample ajax call -->
<script>
$(document).ready(function(){
    $.ajax({
        url: 'submit.php',
        type: 'post',
        data: $('form.a-form').serializeArray(),
        success: function(response){
            ...
        }
    });
});
</script>

The Values will be available in PHP as $_POST['field'][INDEX].

drhelado
  • 33
  • 6
Thomas Venturini
  • 3,500
  • 4
  • 34
  • 43
3

You may use the contain selector:

[name*=”value”]: selects elements that have the specified attribute with a value containing a given substring.

$( document ).on( "keyup", "input[name*='pages_title']", function() {
     alert($(this).val());
});
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
Adnan Ahmad
  • 848
  • 1
  • 13
  • 12
3

Most used is this:

$("input[name='varname[]']").map( function(key){
    console.log(key+':'+$(this).val());
})

Whit that you get the key of the array possition and the value.

hdaleman
  • 41
  • 3
2

You can escape the square brackets with double backslashes like this:

$('input[name="pages_title\\[\\]"]')

Henry
  • 7,721
  • 2
  • 38
  • 38
1

In order to select an element by attribute having a specific characteristic you may create a new selector like in the following snippet using a regex pattern. The usage of regex is intended to make flexible the new selector as much as possible:

jQuery.extend(jQuery.expr[':'], {
    nameMatch: function (ele, idx, selector) {
        var rpStr = (selector[3] || '').replace(/^\/(.*)\/$/, '$1');
        return (new RegExp(rpStr)).test(ele.name);
    }
});


//
// use of selector
//
$('input:nameMatch(/^pages_title\\[\\d\\]$/)').each(function(idx, ele) {
  console.log(ele.outerHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<input type="text" value="2" name="pages_title[1]">
<input type="text" value="1" name="pages_title[2]">
<input type="text" value="1" name="pages_title[]">

Another solution can be based on:

  • [name^=”value”]: selects elements that have the specified attribute with a value beginning exactly with a given string.

  • .filter(): reduce the set of matched elements to those that match the selector or pass the function's test.

  • a regex pattern

var selectedEle = $(':input[name^="pages_title"]').filter(function(idx, ele) {
    //
    // test if the name attribute matches the pattern.....
    //
    return  /^pages_title\[\d\]$/.test(ele.name);
});
selectedEle.each(function(idx, ele) {
    console.log(ele.outerHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<input type="text" value="2" name="pages_title[1]">
<input type="text" value="1" name="pages_title[2]">
<input type="text" value="1" name="pages_title[]">
Community
  • 1
  • 1
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
0
var data = $("input[name='page_title[]']")
  .map(function () {
    return $(this).val();
  })
  .get();
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
  • 8
    Please [edit] your answer to include an explanation of how this works and why it is the solution to the problem described in the question. See [answer]. – Yunnosch Dec 14 '20 at 08:18