views:

298

answers:

3

Hello,

I have a select box defined as shown below. I want to print out the name and email address of each item in the select box as comma seperated values, like

Tom Wayne,[email protected]
Joe Parker,[email protected]
Peter Simons,[email protected]

Any way to accomplish that using JQuery?

<select multiple="multiple" name="search_results">
<option  value="[email protected]">Tom Wane</option>
<option value="[email protected]">Joe Parker</option>
<option value="[email protected]">Peter Simons</option>
</select>

Thank You

+2  A: 

Try this:

$("select").each(function() {
    var options = [];
    $(this).children("option").each(function() {
        var $this = $(this);
        options.push($this.text()+ "," + $this.val());
    });
    alert(options.join("\n"));
});

This will alert you the options for each select individually.

Gumbo
A: 

Something like this:

var s = "";
$("select option").each(function()
{
   var $option = $(this);
   s += $option.text() + ", " + $option.val() + "\n";
});

alert(s);
fforw
+4  A: 

I think is a good example to use Traversing/map:

$('select option').map(function () {
  return $(this).text() + ',' + $(this).val();
}).get().join('\n');
CMS
+1 Nice usage of `map()`!
J-P
Why does map() return the Jquery object? Do you have an example where get isn't used after map?
Ken Fox
Thanks for the reply CMS. But,the code just prints out the names not the email address !.
Scott
Scott, try it out here: http://jsbin.com/acoga ... it *does* print the email addresses, exactly in the way you requested it.
CMS
Thanks CMS ! :)
Scott
You're welcome @Scott, Thanks @J-P
CMS