2016-10-10 101 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>

相关问题