使用jQuery,你如何检查选择菜单中是否有一个选项,如果没有,分配一个选择的选项。
(选择生成与一个应用程序的PHP函数的迷宫,我刚刚继承,所以这是一个快速修复,而我得到我的脑袋周围的那些:)
使用jQuery,你如何检查选择菜单中是否有一个选项,如果没有,分配一个选择的选项。
(选择生成与一个应用程序的PHP函数的迷宫,我刚刚继承,所以这是一个快速修复,而我得到我的脑袋周围的那些:)
当前回答
这是我的函数改变所选的选项。它适用于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');
}
其他回答
这是一个快速脚本,我发现工作… . result被分配给一个标签。
$(".Result").html($("option:selected").text());
我发现了一个很好的方法来检查,如果选项被选中,并选择一个默认时,它不是。
if(!$('#some_select option[selected="selected"]').val()) {
//here code if it HAS NOT selected value
//for exaple adding the first value as "placeholder"
$('#some_select option:first-child').before('<option disabled selected>Wybierz:</option>');
}
如果#some_select没有默认选择选项,则.val()是未定义的
更改选择框上的事件以触发,一旦它发生,则只需拉出所选选项的id属性:-
$("#type").change(function(){
var id = $(this).find("option:selected").attr("id");
switch (id){
case "trade_buy_max":
// do something here
break;
}
});
这是我的函数改变所选的选项。它适用于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');
}
<script type="text/javascript">
$(document).ready(function() {
if (!$("#mySelect option:selected").length)
$("#mySelect").val( 3 );
});
</script>