使用JQuery以逗号分隔值的形式打印列表框的内容

时间:2022-04-08 00:17:43

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,tom@xyz.com
Joe Parker,joe@xyz.com
Peter Simons,peter@xyz.com

Any way to accomplish that using JQuery?

使用JQuery实现这一目标的任何方法?

<select multiple="multiple" name="search_results">
<option  value="tom@xyz.com">Tom Wane</option>
<option value="joe@xyz.com">Joe Parker</option>
<option value="peter@xyz.com">Peter Simons</option>
</select>

Thank You

谢谢

3 个解决方案

#1


2  

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.

这将提醒您单独选择每个选项。

#2


10  

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

我认为使用Traversing / map是一个很好的例子:

$('select option').map(function () {
  return $(this).text() + ',' + $(this).val();
}).get().join('\n');

#3


0  

Something like this:

像这样的东西:

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

alert(s);

#1


2  

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.

这将提醒您单独选择每个选项。

#2


10  

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

我认为使用Traversing / map是一个很好的例子:

$('select option').map(function () {
  return $(this).text() + ',' + $(this).val();
}).get().join('\n');

#3


0  

Something like this:

像这样的东西:

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

alert(s);