简体   繁体   中英

Jquery Multiselect - Trigger event manually?

I'm using the jquery multiselect control from: http://abeautifulsite.net/notebook/62

I need to manually check one of the options via javascript on a specific event.

Whenever I try to change the checked attribute, or trigger a click, call the click function explicitely etc., I the checkbox gets checked but the CSS is never changed and the textbox is never refreshed with the currently selected element(s).

Example: If I want to select the checkbox with the 'TRA' value with javascript code and make sure it behaves properly, how can I achieve this?

<input class="multiSelect" type="text" style="cursor: default;" value="" readonly="readonly"/>

<div class="multiSelectOptions" style="position: absolute; z-index: 99999; display: none;">
    <label class="selectAll">
        <input class="selectAll" type="checkbox"/>
        (All)   
    </label>
    <label>
        <input type="checkbox" value="ADP" name="Attributes"/>
        Adaptation
    </label>
    <label>
        <input type="checkbox" value="TRA" name="Attributes"/>
        Translation
    </label>
</div>  

It seems that you need to set the checked attribute before triggering the click event and then set the checked attribute after too. I'm going to look into it further, but in the meantime, here's the solution

Working Example

relevant jQuery Code

$(function() {
    $('#sample').multiSelect();
    $('#check').click(function() {
        $('input[type="checkbox"][value="TRA"]')
            .attr('checked',true)
            .trigger('click')
            .attr('checked',true);
    });
    $('#uncheck').click(function() {
        $('input[type="checkbox"][value="TRA"]')
            .attr('checked',false)
            .trigger('click')
            .attr('checked',false);
    });
});

relevant HTML

<select id="sample" multiple="multiple">
    <option value=""/>
    <option value="ADP">Adaptation</option>
    <option value="TRA">Translation</option>
</select>
<br/>
<input id="check" type="button" value="Check TRA" style="margin-left: 250px; width: 100px;" />
<br/>
<input id="uncheck" type="button" value="Uncheck TRA" style="margin-left: 250px; width: 100px;" />

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