use*_*123 2 html javascript jquery multi-select optgroup
我有一个带有多个 optgroup 的选择选项。我想从每个组中选择多个值并根据提交时的标签(optgroup)获取值。
HTML代码是
Run Code Online (Sandbox Code Playgroud)<table> <tr> <td>Select</td> <td> <select multiple="multiple" id="multiGrpSel" "> <optgroup label="Indutry Types" id="types"> <option value="1">Private</option> <option value="2">Public</option> <option value="3">Govt</option> </optgroup> <optgroup label="Unit Category" id="unit"> <option value="1">Micro</option> <option value="2">Small</option> <option value="3">Medium</option> </optgroup> </select> </td> </tr> <tr><th align="center"> <input type="button" id="submit" class="button" value="Submit"> </th></tr> </table>
并在提交时
$("#submit").die('click').live('click',function() {
$('#multiGrpSel').find("option:selected").each(function(){
//optgroup label
console.debug('label='+$(this).parent().attr("label"));
//optgroup id
console.debug('id='+$(this).parent().attr("id"));
// values based on each group ??
id = $(this).parent().attr("id");
console.debug('value='+$('#'+id).val());
});
});
Run Code Online (Sandbox Code Playgroud)
如果选择了第一个和第二个选项组中的两个选项,我将获得label & id,但该值变为空白。
输出:
label=Unit Category
id=unit
value=
label=Unit Category
id=unit
value=
label=Industry Types
id=types
value=
label=Industry Types
id=types
value=
Run Code Online (Sandbox Code Playgroud)
实际上,您已经可以访问这些选定选项的值,但实际上您正在尝试从 中获取值optgroup
,而不是从 中获取值,option
因为您使用optgroup's #id
来确定其值,这就是为什么您总是得到该值的空白结果。
请参阅下面的工作代码:
$("#submit").click(function (){
$('#multiGrpSel').find("option:selected").each(function(){
//optgroup label
var label = $(this).parent().attr("label");
//optgroup id
console.log('id='+$(this).parent().attr("id"));
// values based on each group ??
id = $(this).parent().attr("id");
// gets the value
console.log("label: "+label+" value: "+$(this).val())
});
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="multiple" id="multiGrpSel">
<optgroup label="Industry Types" id="types">
<option value="1">Private</option>
<option value="2">Public</option>
<option value="3">Govt</option>
</optgroup>
<optgroup label="Unit Category" id="unit">
<option value="1">Micro</option>
<option value="2">Small</option>
<option value="3">Medium</option>
</optgroup>
</select>
<input type="button" id="submit" value="submit"/>
Run Code Online (Sandbox Code Playgroud)