How to get name and name key from input that have array name

Viewed 346

here is html inputs :

<input name="item[5689]" type="text" value="abcdefgh"></input>
<input name="item[6535]" type="text" value="abcd1"></input>
<input name="item[9856]" type="text" value="abcd"></input>

So need this type of array for post ajax call :

5689 => abcdefgh
6535 => abcd1
9856 => abcd

How it can be achieved by jquery ?

here I try but not success :

$("input[name='item[^]']").each(function() {
  console.log("Name: " + this.name + ", index: " + $(this).index());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="item[5689]" type="text" value="abcdefgh"></input>
<input name="item[6535]" type="text" value="abcd1"></input>
<input name="item[9856]" type="text" value="abcd"></input>

2 Answers

Unfortunately there's no attribute matches expression selector so your best option is to...

  1. Find all the elements (by attribute starts-with selector)
  2. Filter them to make sure they match the expected format
  3. Extract the input value and key from the name and map them to entries
  4. Reduce that to the object result you want

const rx = /^item\[(.+?)]$/

const result = Object.fromEntries(
  jQuery("input[name^='item[']")
    .filter((_, { name }) => rx.test(name))
    .map((_, { name, value }) => [[ name.match(rx)[1], value ]])
    .get())
    
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="item[5689]" type="text" value="abcdefgh">
<input name="item[6535]" type="text" value="abcd1">
<input name="item[9856]" type="text" value="abcd">

jQuery's .map() appears to flatten the array, hence the [[...]] which makes it suitable for Object.fromEntries()

Simpler answer without Regex.

first find all the inputs with name that contains []

via [name*=] notation. then iterate over the tags and take the substring

between [ & ] characters of the name and last get the value via

.val() method (not index() that will give you the index not the value)

$("input[name*='item[']").each(function() {
  console.log("Name: " + this.name.substring(
    this.name.lastIndexOf("[") + 1, this.name.lastIndexOf("]")) + ", index: " + $(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="item[5689]" type="text" value="abcdefgh"></input>
<input name="item[6535]" type="text" value="abcd1"></input>
<input name="item[9856]" type="text" value="abcd"></input>

Related