开发者

JQuery to access Multi-Select Drop down menu

I am working on a multi-select drop-down menu mentioned below

<select class="form-input name="hideLineItemColumns_quote" multiple="true" ">
    <option selected="true" value="part_desc">Description</option>
    <option selected="true" value="part_number">Product</opti开发者_C百科on>
    <option selected="true" value="costEa_line">Cost</option>
</select>

I want to access values & text of all selected options and use them in further logic. I tried doing this

var tempVar = jQuery("Select[@name='hideLineItemColumns_quote'] option:selected").text();
alert(tempVar[0]);

Instead of showing "Description", it shows "D". It combines all three values in one long string. Any ideas what I am doing wrong?

Thanks, Nitesh


tempVar is a string. So you are looking at the first character in that string which is D

In addition, all you options are selected.

Perhaps this is what you meant to do:

var tempVar = [];
jQuery("Select[@name='hideLineItemColumns_quote'] option:selected").each(function () {
                  tempVar.push($(this).text());
});
alert(tempVar[0]);


Your current query is selecting all three option elements. When you call .text() on this set, jQuery assumes you want the text of all three combined.

If you want to deal with them separately, you could iterate via .each() or .map():

// with .each():
$("select[@name='hideLineItemColumns_quote'] option:selected").each(function(idx, el) {
    console.log($(el).text());
});

// with .map():
var options_arr = $("select[@name='hideLineItemColumns_quote'] option:selected").map(function(idx, el) {
    return $(el).text();
}); // => ['Description', 'Product', 'Cost']
console.log(options_arr);

http://jsfiddle.net/hans/kCZDh/1/


I've played with it a bit...

var tempVar = [];
$('select[name="hideLineItemColumns_quote"] option:selected').each(function() {
    var $option = $(this);
    tempVar.push({ text: $option.text(), value: $option.attr('value') });
});
alert(tempVar[0].text);

What it does basically, like one of the other answers, is make an array of the selected items of your list. For each selected items, it creates a tiny object that contains a text and value property so you can access them more intuitively later on. (Like in the alert() line);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜