0

I am trying to get a 2D array using the document.getElementById("clients").value.split(','); as I need to split the 2d array.

I have tried the above code/step.

<input type="hidden" id="clients" name="clients"  value="{{clients}}">

var displayClient = [];
var clients_array = document.getElementByName("clients").value.split(',');

var itemDisp = [];
var arrayLength = clients_array.length;
for (var i = 0; i < arrayLength; i++) {
    displayClient.push(clients_array[i] + ' - ' + clients_array[i]);
    itemDisp.push({ label: displayClient[i]});
}

//the 2d array is as follows
[['1', 'client 1'], ['2', 'client 2']]

the actual result at the moment is: [['1' (new line) 'client 1']... while I would like to get: 1 - client 1...

jurgen.s
  • 124
  • 2
  • 12

1 Answers1

0

For example see function inputHandler.
For more information about transform HTMLCollection to array see Most efficient way to convert an HTMLCollection to an Array

// create elements
fetch('http://jsonplaceholder.typicode.com/users')
.then(res=>res.json())
.then(users => {
  users.forEach(function(user) {
    var input = document.createElement('input');
    input.value = user.name;
    input.name = 'clients';
    document.body.appendChild(input);
    
    inputHandler();
  });
})
.catch(err => {
  throw err;
});

function inputHandler() {
  var inputs = document.getElementsByName('clients');
  inputsArr = Array.prototype.slice.call(inputs);
  inputsArr.forEach(function(element) {
    console.log(element.value);
  });
  // or use that HTMLCollection iterable
  console.log(' HTMLCollection iterable');
  for (var counter = 0; counter < inputs.length; counter++) {
    console.log(inputs[counter].value);
    // or other operations
  }
}
eustatos
  • 686
  • 1
  • 10
  • 21