简体   繁体   中英

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

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/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> <select id="inputYear" class="form-control"> <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>

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/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> <select id="inputYear" class="form-control"> <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM