如何使用 jquery 显示所选选项值

How to show the selected option value using jquery?

本文关键字:选项 显示 何使用 jquery      更新时间:2023-09-26

我能够将数组中的值附加到选择选项中。当我这样做时,我无法在选择框中看到文本值(A1)。但是当我使用警报框时,它显示 A1 作为所选选项。

我的jQUERY代码:

var route=['A1','A2','A3','A4','A5','A6','A7',......,'A50']
$.each(route, function(key, value) {
 $('#room').append($('<option>', { value : key }).text(value)); 
if (!$("#room option:selected").length)
$("#room option[value='0']").attr('selected', 'selected'); 

这是我的 html 代码:

<div data-role="fieldcontain"> 
<select name="room" id="room">  
</select>          
</div>

谁能帮我这个?

试试这个

var route=['A1','A2','A3','A4','A5','A6','A7','A50'], html;
$.each(route, function(key, value) {
  html += '<option value="'+key+'">'+value+'</option>';
});
$('#room').append(html);
if ($("#room").val() !== '0') {
  $("#room").val(0); // using .val() will select the correct option for you, based on it's value attribute
} ​

请参阅: http://jsfiddle.net/tyPFu/

相关文章: