Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

48
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" />

7 months 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>

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs