使用jquery进行选择框控制

时间:2010-09-22 10:29:23

标签: javascript jquery html

我正在使用选择框:

<select name="priority" id="priority">
    <option value="4">Low</option>
    <option value="3" selected="selected">Normal</option>
    <option value="2">High</option>
    <option value="1">Emergency</option>
</select>

当用户选择“紧急”时,将打开一个确认框,如果用户确认,则选择“紧急”。否则应选择“正常”。为此,我使用jquery:

$(document).ready(function() {
    $('#priority').change(function(){
        if($(this).val()=='1'){
            if(confirm("Are you sure this is emergency?")){
                return true;
            }
            else{
                //here some code is needed to select "Normal".
            }
        }
    });
});

现在,我该怎么做?

3 个答案:

答案 0 :(得分:1)

由于您刚刚返回确认案例,因此您可以将逻辑缩短为:

$(function() {
  $('#priority').change(function(){
    if($(this).val()=='1' && !confirm("Are you sure this is emergency?")){
      $(this).val('3');
    }
  });
});​

You can give it a try here

答案 1 :(得分:0)

else{
     $(this).find("option[value=3]").attr("selected","selected");
     //and trigger change after that if you need it
     $(this).change();
    }

答案 2 :(得分:0)

以下代码段应该按照您的要求执行 - 它按ID选择优先级选择元素,然后将所选值设置为3.

else 
{
    $('#priority').val(3);
}