简体   繁体   中英

YUI 3: Set Value to Multiple Select

I using YUI 3, but I have a question about YUI usage.

I have a select tag with some option tags:

 YUI().use( "node", "event", "cssbutton", function(Y){ Y.one('body').addClass('yui3-skin-sam'); Y.one('#btnSel2').on('click',function(){ Y.one('#mySelect').set('value', '5'); }); }); 
 <select id="mySelect" size="10" multiple="true"> <option value="1">Apple</option> <option value="2">Mango</option> <option value="3">PineApple</option> <option value="4">Orange</option> <option value="5">Peach</option> </select> <button id="btnSel2" class="yui3-button">Set Selected</button> 

The above method just cover one value, can i set multiple value from array or string with comma delimited?

If you check yui3/build/dom-base/dom-base.js line 202 you will see this feature is not implemented:

if (options && options.length) {
    // TODO: implement multipe select
    if (node.multiple) {
    } else if (node.selectedIndex > -1) {
        val = Y_DOM.getValue(options[node.selectedIndex]);
    }
}

Here is how we implemented this feature:

 YUI().use( "node", "event", "cssbutton", function(Y){ Y.one('body').addClass('yui3-skin-sam'); Y.DOM.VALUE_GETTERS.select = function(node) { var val = node.value, options = node.options; if (options && options.length) { if (node.multiple) { val = []; for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) { if (option.selected) val.push(Y.DOM.getValue(option)); }; } else if (node.selectedIndex > -1) { val = Y.DOM.getValue(options[node.selectedIndex]); } } return val; }; Y.DOM.VALUE_SETTERS.select = function(node, val) { if (node.multiple && !Y.Lang.isArray(val)) val = [val]; // Allow to set value by single value for multiple selects for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) { if ((node.multiple && val.indexOf(Y.DOM.getValue(option)) > -1) || (!node.multiple && Y.DOM.getValue(option) === val)) { option.selected = true; //Y_DOM.setAttribute(option, 'selected', 'selected'); } } }; Y.one('#btnSel2').on('click',function(){ Y.one('#mySelect').set('value', ['1', '5']); }); }); 
 <script src="http://yui.yahooapis.com/3.18.1/build/yui/yui-min.js"></script> <select id="mySelect" size="10" multiple="true"> <option value="1">Apple</option> <option value="2">Mango</option> <option value="3">PineApple</option> <option value="4">Orange</option> <option value="5">Peach</option> </select> <button id="btnSel2" class="yui3-button">Set Selected</button> 

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