Search code examples
jquerysemantic-ui

Trigger onChange for Semantic UI dropdown


Simply put, I would like to be able to trigger the onChange function in the dropdown for semantic ui.

$(".ui.dropdown").dropdown({onChange:function(value,text){console.log("a");}});

See a fiddle here: http://jsfiddle.net/0mLLscoq/

I want to trigger the onchange without clicking the dropdown and closing it. Simply programmatically forcing a trigger.


Solution

  • I couldn't find any way to do it with the API, but one possible hack is to assign a data-value to each item and then manually trigger the click for that item:

    //HTML
    <div class="ui dropdown">
        <div class="text">Select</div>
        <i class="dropdown icon"></i>
        <div class="menu">
            <div class="item" data-value="Edit">Edit</div>
            <div class="item" data-value="Remove">Remove</div>
            <div class="item" data-value="Hide">Hide</div>
        </div>
    </div>
    
    //JS
    $(".ui.dropdown").dropdown({onChange:function(value,text){console.log("a");}})
                     .find("[data-value='Hide']").trigger("click");
    

    Example Fiddle


    Update (Mar 11th 2016):

    As @Süha mentions in the comments there is a dropdown behavior that allows you to change the value:

    // Will change value and update UI
    $('.dropdown').dropdown('set selected', 'Hide');
    
    // Will only change value
    $('.dropdown').dropdown('set value', 'Hide');
    

    But neither of these will trigger the onchange event.

    Example Fiddle