简体   繁体   中英

refreshing select option without reloading a page javascript

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);
  })

;

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> 

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.

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