javascript 在javascript中选择.js多个选择值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15555359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:11:03  来源:igfitidea点击:

Chosen.js multiple select values in javascript

javascriptjqueryjquery-chosen

提问by Michael

I am using chosen.js to create a multiple select, but instead of processing the form in php, I am trying to use javascript to parse the values. My problem is that I cannot figure out how to retrieve the values from the multiple select.

我正在使用 selected.js 创建一个多选,但不是在 php 中处理表单,而是尝试使用 javascript 来解析值。我的问题是我无法弄清楚如何从多项选择中检索值。

I create the select with:

我创建选择:

<select data-placeholder="Select a category..." name="categories[]" multiple style="width: 350px" class="chzn-select">

and attempt to get the selected values using these javascript calls:

并尝试使用这些 javascript 调用获取选定的值:

$('.chzn-select').chosen().val();

returns null

返回空值

and

$('.chzn-select').chosen().val(0);

returns

回报

{"0":{"jQuery19109988393174677814":730},"length":1,"prevObject":{"0": {"jQuery19109988393174677814":1,"location":{}},"context":{"jQuery19109988393174677814":1,"location":{}},"length":1},"context":{"jQuery19109988393174677814":1,"location":{}},"selector":".chzn-select"}

{"0":{"jQuery19109988393174677814":730},"length":1,"prevObject":{"0": {"jQuery19109988393174677814":1,"location":{}},"context":{"jQuery19109988393174677814":1,"location":{}},"length":1},"context":{"jQuery19109988393174677814":1,"location":{}},"selector":".chzn-select"}

using JSON.stringify()

使用 JSON.stringify()

回答by Andreas Schwarz

You mixed the use of chosen()and val().

您混合使用chosen()val()

The former transforms your selectinto a nice multiple select list, while the latter gets you the value(s) of the selected element(s).

前者将您select转换为一个不错的多选列表,而后者为您提供所选元素的值。

So your JavaScript code would be:

所以你的 JavaScript 代码将是:

// Transforms your select element
$(".chzn-select").chosen();

// Gets the selected value(s)
$(".chzn-select").val();

The val()method will return an array containing each selected option.

val()方法将返回一个包含每个选定选项的数组

I quickly created a jsFiddleto show you how to use the plugin: when you click on the button, you will see the selected values in the console.

我快速创建了一个jsFiddle来向您展示如何使用该插件:当您单击按钮时,您将在控制台中看到选定的值。