Home > Mobile >  How to I call a function when a user selects an option from a form-control
How to I call a function when a user selects an option from a form-control

Time:07-15

How would I make it so that when I select a year, a function is immediately executed. I do not want to include a button, I want the code to execute as soon as a date is selected. I am using HTML, JavaScript, and bootstrap 5

Thank you.

function onSelect() {
  console.log('Hello World!');
}
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X R7YkIZDRvuzKMRqM OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">

<select id="inputYear" >
  <option value="2022">2022</option>
  <option value="2021">2021</option>
  <option value="2020">2020</option>
  <option value="2019">2019</option>
  <option value="2018">2018</option>
</select>

CodePudding user response:

Similar to how a button press is handled (assigning an event listener to the button's "click" event), you assign an event listener to the select's "change" event.

function onSelect(event) {
  console.log('You picked '   event.target.value);
}

document.querySelector("#inputYear").addEventListener("change", onSelect);
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X R7YkIZDRvuzKMRqM OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">

<select id="inputYear" >
  <option value="2022">2022</option>
  <option value="2021">2021</option>
  <option value="2020">2020</option>
  <option value="2019">2019</option>
  <option value="2018">2018</option>
</select>

  • Related