【问题标题】:How to prevent changing of select option after cancelling confirm using jquery?使用jquery取消确认后如何防止更改选择选项?
【发布时间】:2017-02-19 03:53:52
【问题描述】:

所以我有一个选择选项字段,并且我更改了选择字段选项的内容将显示确认消息。我的问题是如何防止在取消确认消息后更改选择选项字段的值。

$('.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
    }
});

【问题讨论】:

标签: javascript jquery html listbox confirm


【解决方案1】:

您需要将选择的选项存储在变量中,如果确认取消,请重新选择它。

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>

【讨论】:

    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-17
      • 2015-04-05
      • 2014-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      相关资源
      最近更新 更多