[英]How to prevent changing of select option after cancelling confirm using 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
}
});
您需要将所选选项存储在变量中,如果确认取消,请重新选择它。
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>
您可以通过存储select的当前值来执行此操作,然后根据需要撤消该操作。
以下使用自定义事件存储数据,并且该自定义事件也会在页面加载时触发,以防您从服务器传递选定的项目
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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.