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?
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();
- 2022 Update -
This logic can now be made more succinct by using ES6 arrow functions.
var items = $("#foo option:selected").map((i, el) => el.textContent.trim()).get();
console.log(items.join());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<select size="4" name="ctl00$ContentPlaceHolder1$ddlSubject" multiple="multiple" id="foo" class="chosen-select" style="height: 250px; width: 250px;">
<option value="Account - I" style="font-style:italic;" disabled="disabled">Account - I</option>
<option value="1" selected="true">Chap1</option>
<option value="2">Chap2</option>
<option value="3" selected="true">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" selected="true">Chap2</option>
<option value="7">Chap3</option>
<option value="8" selected="true">Chap4</option>
</select>
Note that this is not supported in IE.