I am writing a very basic website which involves the user to use a drop down menu to select an option, and it will play a sound when they do.
This works fine if the user wants to pick a different option each time, but not if they play a sound from one <option>, then want to play it again by “selecting” it again. I say “selecting it again” because it’s already selected, so clicking on the select box and picking the same option would not be onChange, which wouldn’t trigger the event.
How can you achieve it so that if you click on an <option>, it will execute that JS regardless if it is selected?
<select onchange="document.getElementById(this.options[this.selectedIndex].value).play()">
<option>Select</option>
<option value="1">Sound one</option>
<option value="2">Sound two</option>
<option value="3">Sound three</option>
<option value="4">Sound four</option>
</select>
I think you would want to bind the click handler as well.
JavaScript with Inline event binding
JavaScript without inline event binding
jQuery
Note: if you are using jQuery 1.7 or higher you should begin using on() instead of bind()