Jquery get input array field
Asked Answered
B

12

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]"]')

Bowie answered 22/10, 2013 at 22:21 Comment(4)
possible duplicate of jQuery selector for inputs with square brackets in the name attributeGrau
Ah, misread question. Close vote is wrong...need to use starts with selector.Grau
@Grau - how would begin with help to get all of them?Elevate
I made a simple plugin that will recursively generate a JSON object representation of these "multidimensional input fields": codepen.io/alexweissman/pen/MyWZdNBidet
R
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.

Roxie answered 22/10, 2013 at 22:33 Comment(1)
This solution has a caveat, if any other input starts with a similar name, it would also be included. e.g "pages_title_secondary"Elevate
E
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[]">
Elevate answered 22/10, 2013 at 22:22 Comment(5)
To iterate over each one, use $('input[name="pages_title[]"]').each(function() { var aValue = $(this).val(); });Delaine
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]Bowie
@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] etcByrn
@Byrn - it is legal, but the naming comes to represent an array, [1] would represent a different array then [2]Elevate
-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.Shirberg
M
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();
Macrophage answered 27/5, 2016 at 8:53 Comment(0)
G
14

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.

Grau answered 22/10, 2013 at 22:29 Comment(5)
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?Elevate
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"Grau
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.Elevate
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.Elevate
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.Karisa
S
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;
});
Sidonia answered 16/10, 2014 at 13:46 Comment(0)
B
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()); 
});
Bombard answered 5/3, 2014 at 19:55 Comment(1)
That's great answer. It help a lot of me.Aperiodic
D
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].

Downwards answered 2/6, 2015 at 13:42 Comment(0)
P
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());
});
Pilfer answered 18/9, 2017 at 17:9 Comment(0)
H
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.

Harvell answered 31/7, 2019 at 14:32 Comment(0)
S
2

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

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

Sizemore answered 23/2, 2016 at 21:55 Comment(0)
S
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[]">
Sharmainesharman answered 18/9, 2017 at 18:17 Comment(0)
G
0
var data = $("input[name='page_title[]']")
  .map(function () {
    return $(this).val();
  })
  .get();
Galba answered 14/12, 2020 at 8:16 Comment(1)
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 How to Answer.Geniegenii

© 2022 - 2024 — McMap. All rights reserved.