0
How do I insert an array value into a textbox?
Let's say I have an array: var myArray = [ {name: "John", age: "25"}, {name"Susan", age:"30"} ] And I have a name textbox: var nameField = document.getElementById('#name'); And when I insert the name in a prompt box: var userQuestion = prompt("What is your name", ''); Now I want the name e.g Susan to show up in the textbox after filling in the prompt box. NOTE: I have written most of the code, I just want an example of how to pass an array value into a textbox.
2 Answers
+ 10
In that case you'll access the element inside the array with its index and assign it to the DOM properties like following:-
nameField.textContent = myArray[1].name;
+ 2
// if you would like to use the input prompt, userQuestion to fetch a user name and its age out of the array, myArray if it exists in the array:
var names = myArray.map(function(a) {return a.name} // names is an array with all the names only
var ages = myArray.map(function(a) {return a.age} // ages is an array with all the ages only
var userIndex = names.indexOf(userQuestion); // look for user index
if(userIndex !== -1) {
nameField.value = names[userIndex]; // update user name if exist
ageField.value = ages[userIndex]; // update age input box
}
else {
alert("name " + userQuestion + " does not exist!");
}