Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery get input array field

Tags:

jquery

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

like image 981
abiku Avatar asked Oct 22 '13 22:10

abiku


People also ask

How to get array input value in js?

var input = document. getElementsByName('array[]'); The document. getElementsByName() method is used to return all the values stored under a particular name and thus making input variable an array indexed from 0 to number of inputs.

How do you input values into an array?

To take input of an array, we must ask the user about the length of the array. After that, we use a Java for loop to take the input from the user and the same for loop is also used for retrieving the elements from the array.

What is map in jQuery?

The jQuery map() function translates all items in an object or in array to a new array of items. It applies a function to each item of the object or array and maps the results into a new array.


2 Answers

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.

like image 111
97ldave Avatar answered Sep 24 '22 17:09

97ldave


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[]">
like image 22
Rafael Herscovici Avatar answered Sep 23 '22 17:09

Rafael Herscovici