mel*_*yal 205 javascript forms jquery dom html-select
使用jQuery,如何检查在选择菜单中是否选择了选项,如果没有,则将其中一个选项指定为选中.
(选择是在我刚刚继承的应用程序中使用迷宫般的PHP函数生成的,所以这是一个快速解决方案,而我可以解决这些问题:)
Joe*_*oni 267
虽然我不确定你想要完成什么,但这段代码对我有用.
<select id="mySelect" multiple="multiple">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
<script type="text/javascript">
$(document).ready(function() {
if (!$("#mySelect option:selected").length) {
$("#mySelect option[value='3']").attr('selected', 'selected');
}
});
</script>
Run Code Online (Sandbox Code Playgroud)
Fly*_*wat 30
不需要为此使用jQuery:
var foo = document.getElementById('yourSelect');
if (foo)
{
if (foo.selectedIndex != null)
{
foo.selectedIndex = 0;
}
}
Run Code Online (Sandbox Code Playgroud)
Gav*_*vin 13
这个问题已经很久了,并且有很多观点,所以我只想把一些东西放在那里,这将有助于一些我确定的人.
要检查select元素是否包含任何选定项:
if ($('#mySelect option:selected').length > 0) { alert('has a selected item'); }
Run Code Online (Sandbox Code Playgroud)
或检查选择是否没有选择:
if ($('#mySelect option:selected').length == 0) { alert('nothing selected'); }
Run Code Online (Sandbox Code Playgroud)
或者如果您处于某种循环中并想要检查当前元素是否被选中:
$('#mySelect option').each(function() {
if ($(this).is(':selected')) { .. }
});
Run Code Online (Sandbox Code Playgroud)
检查循环中是否未选择元素:
$('#mySelect option').each(function() {
if ($(this).not(':selected')) { .. }
});
Run Code Online (Sandbox Code Playgroud)
这些是实现此目的的一些方法.jQuery有许多不同的方法来完成同样的事情,所以你通常只选择哪一个看起来效率最高.
Ale*_*ton 12
lencioni的回答是我推荐的.您可以更改选项的选择器,('#mySelect option:last')使用" #mySelect option[value='yourDefaultValue']" 选择具有特定值的选项. 更多选择器.
如果您正在广泛使用客户端上的选择列表,请查看此插件:http: //www.texotela.co.uk/code/jquery/select/.如果您想查看更多使用选择列表的示例,请查看源代码.
小智 9
这是我改变所选选项的功能.它适用于jQuery 1.3.2
function selectOption(select_id, option_val) {
$('#'+select_id+' option:selected').removeAttr('selected');
$('#'+select_id+' option[value='+option_val+']').attr('selected','selected');
}
Run Code Online (Sandbox Code Playgroud)
小智 7
<script type="text/javascript">
$(document).ready(function() {
if (!$("#mySelect option:selected").length)
$("#mySelect").val( 3 );
});
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
500169 次 |
| 最近记录: |