So, I am reading some data with document.getElementById which is already an array.But somehow when I am reading it, it is resulting in a string insted.
I am using the document.getElementById('clients').value, and apparently this returns a string, while I would like to get an array instead.
var clients = [];
clients = document.getElementById("clients").value;
alert(clients);
console.log(clients);
for(var i =0; i < clients.length; i++){
var client = clients[i].toString().split(',');
alert(client);
}
//console.log(clients) gets:
["[['1'", " 'client1']", " ['2'", " 'client2']", " ['3'", " 'client3']]"]
when I am alerting the client from the for loop, I am getting each and every character found in clients one by one. While I would like to get an object to split it. Thanks a lot in advance.
3 Answers 3
I have something like this: [['1', 'client1'], ['2', 'client2'], ['3', 'client3']] and would like to get: 1 - client1.....
The .value should be valid JSON or RegExp or String methods need to be used to convert invalid JSON to valid JSON. Note the single quotes at HTML attribute surrounding the value and double quotes within the value of the attribute
[["1", "client1"], ["2", "client2"], ["3", "client3"]]
You can then use JSON.parse() to convert JSON string to JavaScript object and use for..of loop to iterate each element of each nested array.
let value = JSON.parse(clients.value);
for (let [a, b] of value) {
console.log(a, b)
}
<input id="clients" value='[["1", "client1"], ["2", "client2"], ["3", "client3"]]'>
3 Comments
.value is not valid JSON. Can you include the full .outerHTML of the element at the question?Unexpected token u is probably due to a undefined. Make sure you retreive the input's value correctly.document.getElementById("clients").value
is a string, not an array. If you do :
for(var i =0; i < clients.length; i++)
you are actually iterating over every letter of the string, not every word.
What you can do is type client1,client2,client3 in your input field, then split them this way :
const clients = document.getElementById("clients").value.split(",") // ["client1","client2","client3"]
Comments
If you want to input an array using an <input> tag, with values separated by commas or spaces, you have no choice but to use it with type="text", which will return you a string.
You then have to trim and split that string to build your array. You can use a regex to split the string on multiple separators:
function getClients() {
const stringClients = document.getElementById("clients").value;
const clients = stringClients.trim().split(/[\s,]+/);
console.log('clients:', clients);
}
Enter a comma or space separated list:<br>
<input type="text" id="clients" oninput="getClients()">
clientsis.clientslooks likeclients?.valueis at the question, and what the expected result is, it would help resolve the inquiry. See stackoverflow.com/help/mcve, stackoverflow.com/help/how-to-ask