html选择中的jquery get selected选项
我试图通过jquery知道用户是否已经在我的html选择元素中选择了一个选项。如果仍然没有,我会自动将所选值设置为第一个选项。然而,这是行不通的 我这样做对吗 注意:当select元素通过$'inputRoom'加载时,我正在使用从数据库获得的数据填充select元素。就绪….: 更新:现在工作正常。。。乔伊和菲利克斯都是对的。。。此外,我发现我的淘汰代码的定位也引起了一些问题。。。修正了。。谢谢html选择中的jquery get selected选项,jquery,json,Jquery,Json,我试图通过jquery知道用户是否已经在我的html选择元素中选择了一个选项。如果仍然没有,我会自动将所选值设置为第一个选项。然而,这是行不通的 我这样做对吗 注意:当select元素通过$'inputRoom'加载时,我正在使用从数据库获得的数据填充select元素。就绪….: 更新:现在工作正常。。。乔伊和菲利克斯都是对的。。。此外,我发现我的淘汰代码的定位也引起了一些问题。。。修正了。。谢谢 if ($('#inputRoom option:selected').text()
if ($('#inputRoom option:selected').text() == null || $('#inputRoom option:selected').text() == "")
{
$('#inputRoom option').eq(0).attr('selected', 'selected');
}
您可以使用
注
正如@Felix Kling在评论中所说,如果你没有任何空选项,那么你不需要这样做,第一个选项将默认被选中
if (!$('#inputRoom').val())
{
$('#inputRoom option:first').attr('selected', 'selected');
}
假设您的SELECT元素是这样的
$(function(){
if (($("#inputRoom").val()=="") ||($("#inputRoom").val()=="0") )
{
$('#inputRoom option').eq(1).attr('selected', 'selected');
}
});
工作示例第一个选项始终由浏览器自动选择,您不需要JavaScript。在json中添加选项之前或之后,您运行此选项的时间可能重复?
$(function(){
if (($("#inputRoom").val()=="") ||($("#inputRoom").val()=="0") )
{
$('#inputRoom option').eq(1).attr('selected', 'selected');
}
});
<select id="inputRoom">
<option value="0" selected></option>
<option value="1">1</option>
<option value="2" >3</option>
</select>