简体   繁体   中英

Javascript - Bind a click event to multiple <options> elements

I have a select menu, which I would like to bind a single click event to each of the <option> elements. The purpose of this is to add a class to the <option> elements when ever it is clicked/selected. Here is my html and Javascript. I am lacking a way to select the <option> elements and bind the event to them. Any and all assistance would be appreciated.

Html:

<div class="row">
  <div class="small-12 columns">
    <label>Select Menu
      <select id="SelectMenu">
        <option value="husker">Husker</option>
        <option value="starbuck">Starbuck</option>
        <option value="hotdog">Hot Dog</option>
        <option value="apollo">Apollo</option>
      </select>
    </label>
  </div>
</div>

Javascript

function myFunction() {
  console.log("Click Event");
}
var options = document.getElementById('SelectMenu');
for ( var i = 0; i < options.length; i++ ) {
  console.log(options[i].value);
  options[i].addEventListener('click', myFunction, false)
}

Code example

Let's see what your code does:

function myFunction() {
  console.log("Click Event");
}

Pretty straightforward, a function.

Next up,

var options = document.getElementById('SelectMenu');

So, options is assigned the #SelectMenu element. Ok.

for ( var i = 0; i < options.length; i++ ) {
  console.log(options[i].value);
  options[i].addEventListener('click', myFunction, false)
}

Now, here you start to get it a little wrong.

You don't have to add a listener to each and every option element in there.

The select element (yout options variable) emits a change event every time you select another option.

So you can simply do

options.addEventListener('change', myFunction)

and that's it.

If you want to know which option element was clicked you should also define an event parameter to your callback function, like this

function myFunction(e) {
  //e.target is the <select> element
  console.log(e.target.value);
  console.log("Click Event");
}

There is not much point to adding a class to the clicked option element since you cannot style them.

UPDATE: Since you ask specifically to add a class to the selected option anyway, here's how you can do it:

function myFunction(e) {
  //e.target is the <select> element
  console.log(e.target.selectedOptions[0]);
  console.log(e.target.value);
  console.log("Click Event");
}

Cheers Frederick.

better to create one event for the select then check the value in the event

function selectClicked(id){
  console.log(id);
  myFunction() ;
}
function myFunction() {
  console.log("Click Event");
}
var options = document.getElementById('SelectMenu');
options.setAttribute("onchange", function(){selectClicked(options.value);});

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