I need the text value of selected options in a multiple select returned as a “sentence” – just to join the strings, separated by a comma and a space.
The HTML generated for the select looks like this:
<select id="foo_bazs_attributes_0_bar_ids" name="foo[bazs_attributes][0][bar_ids][]" multiple="multiple" data-validate="true">
<option value="1">I</option>
<option value="2">Want</option>
<option value="3">a</option>
<option value="4">Sentence</option>
</select>
So I need my function to return “I, Want, a, Sentence”.
To do this with jQuery, I found the following (at http://calisza.wordpress.com/2009/03/29/6-jquery-snippets-you-can-use-to-manipulate-select-inputs/):
var foo = [];
$('#multiple :selected').each(function(i, selected){
foo[i] = $(selected).text();
});
so I wrote the following in my CoffeeScript file:
$.fn.selectedToSentence = () ->
arr = []
$('this :selected').each (i, sel) ->
arr[i] = $(sel).html()
arr.join(", ")
but it never returns the string.
— edit —
I am calling it like:
$(‘select[id$=”_bar_ids”]’).selectedToSentence()
— /edit —
— edit 2 —
at the CoffeeScript site, it shows the above script as compiling to:
var $;
$ = jQuery;
$.fn.selectedToSentence = function() {
var arr;
arr = [];
$('this :selected').each(function(i, selected) {
return arr[i] = $(selected).text();
});
return arr.join(", ");
};
— /edit 2 —
I have also tried the following syntaxes:
$(@ :selected).each ...
$('@ :selected').each ...
$("#{@} :selected").each ...
all without success.
I’ve Googled, and looked around SO, perhaps with the wrong search terms, because I’m coming up empty.
I feel like it’s just a syntactical thing. What am I doing incorrectly?
This isn’t a CoffeeScript issue, it’s just a plain old jQuery issue. In particular “
'this :selected'” isn’t a valid selector in CSS or jQuery (thisis a variable in JavaScript but it’s meaningless in a selector string). If you want to use a CSS selector only on children of a certain element (likethis, in your scenario) you can pass that element as the second parameter to$, e.g.: