Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
JavaScript - add selected array variable to html Form Input tag

By clicking on the button onclick="nextText()" I am able to select and display the next element in the myText array. This shows up in div id="target". I'll like to use input tag - input id="target" value="" so that I can submit the selected element to a database with a form but selected element does not show up in input field. I'm a newbie, is there a way to do this?

var target = document.getElementById('target');
var counter = 0;
var myText = [
  "Orange",
  "Avocados",
  "Banana",
  "Berry",
  "Apple"
];

function nextText() {
  counter += 1;
  if (counter > myText.length - 1) {
    counter = 0;
  }
  target.innerHTML = myText[counter];
}
<div>
  <div id="target">Fruits</div>
</div>
<input type="button" onclick="nextText()" value="change Text" />

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

For fun I changed your array to a <datalist> (so, the user can choose either to press the button or start writing in the input an get suggestions), but it has the same kind of functionality - you ca see the function that you made is just part of an event listener.

So, to answer your question: To change the value of <input>, assign the value to .value (here e.target.form.fruits.value).

var counter = 0;

document.forms.form01.change.addEventListener('click', e => {
  counter++;
  if (counter > e.target.form.fruits.list.children.length - 1) {
    counter = 0;
  }
  e.target.form.fruits.value = e.target.form.fruits.list.children[counter].value;
});

/*this submit event listener is just for testing
 depending on your use case, do something else...*/
document.forms.form01.addEventListener('submit', e => {
  e.preventDefault();
  let formData = new FormData(e.target);
  console.log([...formData.values()]);
});
<div>
  <div id="target">Fruits</div>
</div>
<form name="form01">
  <input list="fruitsList" name="fruits" />
  <datalist name="fruitsList" id="fruitsList">
    <option value="Orange">
    <option value="Avocados">
    <option value="Banana">
    <option value="Berry">
    <option value="Apple">
  </datalist>
  <input name="change" type="button" value="change Text" />
  <button>Submit</button>
</form>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!