Home > Mobile >  JQuery select name array with unknown id
JQuery select name array with unknown id

Time:07-19

I have multiple inputs as an array like this:

<input name="data[extras][1][id]" value="1">
<input name="data[extras][1][netto]">
<input name="data[extras][1][tax]">
<input name="data[extras][1][brutto]">

<input name="data[extras][2][id]" value="2">
<input name="data[extras][2][netto]">
<input name="data[extras][2][tax]">
<input name="data[extras][2][brutto]">

i got all extras with:

let extras = $('input[name^=data\\[extras\\]]');

now i would like to iterate through all to create an array out of it but i need for the id for further actions (the 1 or the 2).

i would like to achive something like this:

let id = $('input[name^=data\\[extras\\]\\[UNKNOWN ID\\]\\[id\\]]').val();

i hope anybody can help me.

Greetings

CodePudding user response:

you can receive all ids in jquery like this

$('document').ready(function(){
  var values = $('input[name$=\\[id\\]]').map(function(){return $(this).val();}).get();
console.log(values); });

CodePudding user response:

Maybe you could loop trough the inputs and in the loop get the id/index via regexp from the name attribute to query that [id] input?

data\[extras\]\[(\d)\]

CodePudding user response:

Unclear what your expected output would be, but you can easily loop over the collection of elements and parse out the number and the string.

var inputs = document.querySelectorAll('[name^="data\[extras\]"]');
const grouped = Array.from(inputs).reduce(function(o, input) {
  const parts = input.name.match(/^data\[extras\]\[(\d )\]\[(.*)\]$/);
  const index = parts[1];
  const key = parts[2];
  o[index] = o[index] || {};
  o[index][key] = input.value;
  return o;
}, {});

console.log(Object.values(grouped))
<input name="data[extras][1][id]" value="1-i">
<input name="data[extras][1][netto]" value="1-n">
<input name="data[extras][1][tax]" value="1-t">
<input name="data[extras][1][brutto]" value="1-b">

<input name="data[extras][2][id]" value="2-i">
<input name="data[extras][2][netto]" value="2-n">
<input name="data[extras][2][tax]" value="2-t">
<input name="data[extras][2][brutto]" value="2-b">

  • Related