2010-09-22 46 views
1

我用一個選擇框:選擇框控件與jQuery

<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". 
      } 
     } 
    }); 
}); 

現在,我該怎麼做?

回答

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

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

下面的代碼段應該做你所追求的 - 它選擇由ID優先選擇元素,然後將所選擇的價值爲3

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