简体   繁体   English

禁用jQuery提取选择选项值

[英]jQuery fetch disabled select option value

<select id="test_me" name="test_me" disabled>
 <option value="">Please select</option>
 <option value="1">Test One</option>
 <option value="2" selected>Test Two</option>
 <option value="3">Test Three</option>
</select>

<input type="hidden" value="" name="test_hidden" id="test_hidden">

Here option Test Two is selected and disabled. 在这里,选择Test Two并被禁用。 The below code fetches select value when dropdown is enabled and value is changed. 启用下拉菜单并更改值后,以下代码获取选择值。

//pass value to hidden input
$('#test_me').change(function () {
    var id = $(this).val();
    $('input#test_hidden').val(id);
})

How can I pass selected option value ie 2 to my hidden input, when dropdown is disabled and value is selected ? 禁用下拉菜单并选择值时,如何将所选的选项值(即2传递给隐藏的输入?

This issue is reported at http://bugs.jquery.com/ticket/13097 and marked as wont fix. http://bugs.jquery.com/ticket/13097上报告了此问题,并将其标记为“无法修复”。 for reason: 原因:

The long-standing logic in .val() ensures that we don't return disabled options in a select-multiple. .val()中的长期逻辑确保我们不会以select-multiple返回禁用的选项。 The change just applies the same behavior for select-one now for consistency. 为保持一致性,此更改仅将相同的行为应用于选择一个。

Alternative for this would be to use selectedindex property of select to target option by index: 替代方法是使用select的selectedindex属性按索引定位到目标选项:

$("#test_me option").eq($("#test_me").prop("selectedIndex")).val();

Complete Snippet: 完整摘要:

var id =  $("#test_me option").eq($("#test_me").prop("selectedIndex")).val();;
$('input#test_hidden').val(id);
<script type="text/javascript">
//pass value to hidden input
    $(document).ready(function(e) {

    var sel = $("#test_me").val();
    $("#test_hidden").val(sel);

    });

   </script>


<select id="test_me" name="test_me" disabled>
 <option value="">Please select</option>
 <option value="1">Test One</option>
 <option value="2" selected>Test Two</option>
 <option value="3">Test Three</option>
</select>

<input type="hidden" value="" name="test_hidden" id="test_hidden">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM