Jquery get input array field

Jquery

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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[]">

Solution 3 - Jquery

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

var values = $("input[name='pages_title[]']").map(function(){return $(this).val();}).get();

Solution 4 - Jquery

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.

Solution 5 - Jquery

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;
});

Solution 6 - Jquery

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()); 
});

Solution 7 - Jquery

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].

Solution 8 - Jquery

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());
});

Solution 9 - Jquery

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.

Solution 10 - Jquery

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

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

Solution 11 - Jquery

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[]">

Solution 12 - Jquery

var data = $("input[name='page_title[]']")
  .map(function () {
    return $(this).val();
  })
  .get();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionabikuView Question on Stackoverflow
Solution 1 - Jquery97ldaveView Answer on Stackoverflow
Solution 2 - JqueryRafael HerscoviciView Answer on Stackoverflow
Solution 3 - Jqueryuser3021515View Answer on Stackoverflow
Solution 4 - JqueryepascarelloView Answer on Stackoverflow
Solution 5 - JqueryLimitless isaView Answer on Stackoverflow
Solution 6 - JqueryGregory R.View Answer on Stackoverflow
Solution 7 - JqueryThomas VenturiniView Answer on Stackoverflow
Solution 8 - JqueryAdnan AhmadView Answer on Stackoverflow
Solution 9 - JqueryhdalemanView Answer on Stackoverflow
Solution 10 - JqueryHenryView Answer on Stackoverflow
Solution 11 - JquerygaetanoMView Answer on Stackoverflow
Solution 12 - JqueryMD YAHYAView Answer on Stackoverflow