0

I have select option in HTML for which i have used Change event listener for triggering some event. Though the event is triggered first but selecting same option for second time without reloading page isn't triggering event. please help

 learnPiano.addEventListener("change",function(){
    console.log(learnPiano.value,'value');
    learn.guidePlaying(learnPiano.value);
  })

;

laxman khanal
  • 998
  • 1
  • 8
  • 18
  • `onchange` is fired when a value _changes_ . Selecting an already selected option doesn't _change_ the value of an select element. – Teemu Jan 02 '16 at 11:57
  • Try searching better, it's a duplicate - [here](http://stackoverflow.com/questions/11877527/html-select-trigger-javascript-onchange-event-even-when-the-option-is-not-cha) – Sergius Jan 02 '16 at 11:58

2 Answers2

1

change doesn't fire every time. change is only fired when the value has actually been changed. when you select the same value the event does not dispatch.

so, instead use "mouseup" Even Listener.

Click on select only fires when an option has actually been clicked. so i believe it will work as you would expect.

learnPiano.addEventListener("click",function(){
    console.log(learnPiano.value,'value');
    learn.guidePlaying(learnPiano.value);
});

EDIT:

I have Modified the code to clarify because of your last comment.

You must use the "mouseup" on the select tag itself. look at this code snippet and check the console log for the outputs. it works for me on every test.

you can disregard the CSS code completely it's just for the ease of viewing

// i wasn't sure whare lean was so i created a simple object.
// i'm sure you would be able to implement it
var learn = {
  guidePlaying: function(value) {
    console.log("guidePlaying method works");
    console.log(value);
  }
};


select.addEventListener("mouseup",function(){
  
  // this line is decided upon event fire and is the currently selected value
  var selectedValue =  select.options[select.selectedIndex].text;
  
    console.log(selectedValue,'value');
    learn.guidePlaying(selectedValue);
});
select {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100px;
  height: 70px;
  font-size: 18px;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <select id="select">
      <option value="">Any</option>
      <option value="">kind</option>
      <option value="">of</option>
      <option value="">selection</option>
      <option value="">works</option>
  </select>
  </body>
</html>
-1

Change Event will only trigger when you change your selection.


If a value is already selected & if you are trying to select the same value again, Event will not trigger.

Consider this Select

<select id="sel">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
</select>

If after selecting 'Volvo', again if you try to select 'Volvo', Event will not trigger.

subi_speedrunner
  • 901
  • 3
  • 9
  • 17