I'm trying to compare the differences between jQuery and JavaScript in a project, but I can't seem to figure out how to rewrite one function because I'm not sure how I'm supposed to reference a jQuery object. I'm concatenating a string to pass as AJAX parameters. Here is the JavaScript:
function getSelectValues(select) {
var values = "";
var sep = "";
for(var i = 0; i < select.length; i++) {
if (select.options[i].selected) {
values += sep + (select.options[i].value);
sep = ", ";
}
}
return values;
}
I thought the below might be the jQuery equivalent, passing in $(this), but I can't seem to get it to work. I wanted it to return empty string if nothing is selected, but it's returning null instead.
function getSelectValues(select) {
var values = "";
var sep = "";
$("option:selected", select).each(function(){
values += sep + ($(this.val()));
sep = ", ";
});
return values;
}
I also tried:
$(select).each(function(){
$("option:selected", this).each(function(){
values += sep + ($(this.val()));
sep = ", ";
});
});
That didn't work either.