2016-10-10 85 views
0

所以我有一個選擇選項字段,我會更改選擇字段的確認信息選項。我的問題是如何在取消確認消息後防止更改選擇字段的值。如何在使用jquery取消確認後防止更改選擇選項?

$('.changeScoreFem').on('change', function(){ 
    if (confirm('Are you sure to change this score?')) { 
     //continue to change the value 
    } else { 
     //else do not change the selecoption field value 
    } 
}); 
+2

的可能的複製[ jQuery防止改變選擇](http://stackoverflow.com/questions/5426387/jquery-prevent-change-for-select) – Dekel

回答

2

您可以通過存儲選擇當前值做到這一點,然後根據需要取消它。

繼使用自定義事件來存儲數據和自定義事件的情況下,也引發了對頁面加載你通過從服務器選擇的項目

var $sel = $('.changeScoreFem').on('change', function(){ 
    if (confirm('Are you sure to change this score?')) { 
     // store new value   
     $sel.trigger('update'); 
    } else { 
     // reset 
     $sel.val($sel.data('currVal'));   
    } 
}).on('update', function(){ 
    $(this).data('currVal', $(this).val()); 
}).trigger('update'); 

DEMO

2

您需要將選定的選項存儲在變量中,如果確認取消,請重新選擇它。

var selected = $(".changeScoreFem option:selected"); 
 
$(".changeScoreFem").on("change", function(e){ 
 
    if (confirm("Are you sure to change this score?")) 
 
     selected = $(this).find("option:selected"); 
 
    else 
 
     selected.prop("selected", true); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select class="changeScoreFem"> 
 
    <option>Option 1</option> 
 
    <option>Option 2</option> 
 
    <option>Option 3</option> 
 
</select>

相關問題