Skip to content
Advertisement

Semantic UI dropdowns: prevent onchange event from firing when selected option is changed programmatically

When you change selected value of a dropdown with a change event handler programmatically in standard HTML, that event is not fired. For example, if I do:

document.getElementById("my_select").value = "foo";

the onchange event handler of the dropdown is not executed (it only responds to user-initiated events).

I am converting all dropdowns in my code to Semantic UI (which is a great library, BTW). However, the problem is that now the onchange event fires regardless of whether the change was initiated by user interaction or by some JS function.

So, when I do this:

$('#my_select').dropdown('set selected', 'foo');

the onchange event is fired.

Here is the fiddle that shows both behaviors:

FIDDLE

So, my questions are:

  • Is there another way (other than “set selected”) to select one of the options in a dropdown that will not fire onchange event?
  • If not, is there a way to prevent the event from firing?

Thanks!

Advertisement

Answer

To get the behaviour you desire you need to trick the system into thinking you’ve already selected the option you wish you select.

$(document).ready(function() {
	$('.ui.dropdown').dropdown();

	$('#change_button').click( function() {
    //set the value to the value you want
		$('#semantic_select')[0].value='3';
    //now use the semantic ui function
		$('#semantic_select').dropdown('set selected', '3');

	});
});
<link href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"></script>

<select id="semantic_select" class="ui dropdown" onchange="alert('Semantic Changed')">
	<option value=""></option>
	<option value="1">One</option>
	<option value="2">Two</option>
	<option value="3">Three</option>
</select>
<input id="change_button" type="button" value="Change" /><br /><br />

By setting the value, then calling the dropdown function the system thinks you’ve already selected the value you’re setting, so the change event doesn’t fire.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement