Question

I need to get text of item by values in multiple select box. I have tried this code but it give me overall selected text with no separation or spacing.

if ($("#<%=ddlSubject.ClientID %>").val()) {
    var values = $("#<%=ddlSubject.ClientID %>").val();
    if (values.indexOf(',') != -1) {
        values = $(values).split(',');
    }
    var texts = $("#<%=ddlSubject.ClientID %> :selected").text();
    alert(texts);
    if (texts.indexOf(',') != -1) {
        texts = $(texts).split(',');
    }
}
});

This is my rendered html select list

<select size="4" name="ctl00$ContentPlaceHolder1$ddlSubject" multiple="multiple" id="ctl00_ContentPlaceHolder1_ddlSubject" class="chosen-select" style="height: 250px; width: 250px; display: none;">
    <option value="Account - I" style="font-style:italic;" disabled="disabled">Account - I</option>
    <option value="1">Chap1</option>
    <option value="2">Chap2</option>
    <option value="3">Chap3</option>
    <option value="4">Chap4</option>
    <option value="Joint Venture" style="font-style:italic;" disabled="disabled">Joint Venture</option>
    <option value="5">Chap1</option>
    <option value="6">Chap2</option>
    <option value="7">Chap3</option>
    <option value="8">Chap4</option>
</select>

Above code give me text like this "chap1chap2chap3" if these item are selected. I want some text separation using ',' or any thing else. How can I get the selected text?

Was it helpful?

Solution

The map() function can be used to create an array of whatever values you require. Try this:

var items = $("#<%= ddlSubject.ClientID %> option:selected").map(function() {
    return $(this).text();
}).get();
console.log(items.join());

Example fiddle

OTHER TIPS

You can use .map to create an array of selected text:

var texts = $("#<%=ddlSubject.ClientID %> :selected").map(function() {
    return $(this).text();
}).get();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top