jQuery 如何撤消选择更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3963855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:25:58  来源:igfitidea点击:

jQuery how to undo a select change

jquery

提问by Alec

I have a select box, and I'd like to add a confirm before changing it to a specific option. Example:

我有一个选择框,我想在将其更改为特定选项之前添加一个确认。例子:

<select name="select">
    <option value="foo" selected="selected">foo</option>
    <option value="bar">bar</option>
</select>??????????????????
$('select').change(function() {
    var selected = $(this).val();

    if (selected == 'bar') {
        if (!confirm('Are you sure?')) {
            // set back to previously selected option
        }
    }
});

I'm thinking about adding a hidden input field and update its value every time the select is changed. That way I can retrieve the previous value in the changefunction. Example:

我正在考虑添加一个隐藏的输入字段并在每次更改选择时更新其值。这样我就可以检索change函数中的先前值。示例

<input type="hidden" name="current" value="foo" />
$('select').change(function() {
    var selected = $(this).val();
    var current = $('input[name=current]').val();

    if (selected == 'bar') {
        if (!confirm('Are you sure?')) {
            $(this).val(current);
            return false;
        }
    }

    $('input[name=current]').val(selected);
});

Is there an easier/better way to accomplish this?

有没有更简单/更好的方法来实现这一目标?

回答by lonesomeday

Rather than using a global variable (evil!) or a hidden element (abuse of the DOM) you can use the $.datafeature:

您可以使用以下$.data功能,而不是使用全局变量(邪恶!)或隐藏元素(滥用 DOM):

$('select').change(function() {
    var selected = $(this).val();

    if (selected == 'bar') {
        if (!confirm('Are you sure?')) {
            $(this).val($.data(this, 'current'));
            return false;
        }     
    }

    $.data(this, 'current', $(this).val());
});

回答by Jintae Joo

Hope this would help.

希望这会有所帮助。

$( YOUR_SELECT_ELEMENT ).on({
    "ready": function (e) {
        $(this).attr("readonly",true);
    },
    "focus": function (e) {
        $(this).data( { choice: $(this).val() } );
    },
    "change": function (e) {
        if ( ! confirm( "Change selected option, proceed?" ) ){
            $(this).val( $(this).data('choice') );
            return false;
        } else {
            $(this).attr("readonly",false);
            return true;
        }
    }
});

I'm not sure 'return false' is effective for remove the attribute 'readonly'.

我不确定 'return false' 对删除属性 'readonly' 是否有效。

回答by Raman Singh

$(document).on('change','.change_response_status',function()
{
    var responseStatusId = this.id;
    var responseID = $("#"+responseStatusId).attr('data-id');
    var previouesSatatus = $("#hidden_response_id_"+responseID).val();
    var confirmstatus = confirm("Are you sure you want to change status for this item?");
    var currentSelectedValue = $(this).val();

    if(confirmstatus==true)
    {
        $("#hidden_response_id_"+responseID).val(currentSelectedValue);
    }
    else
    {
        $(this).val(previouesSatatus);
        $("#hidden_response_id_"+responseID).val(previouesSatatus);
        return false;
    }
    return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select data-id="2" id="response_id_2" class="change_response_status" name="status">
    <option value="1">Accept</option>
    <option value="2" selected="selected">No Respond</option>
    <option value="3">Reject</option>
</select>
<input class="hidden_response_class" id="hidden_response_id_2" type="hidden" value="1" name="hidden_response_staus">

This is best way to display already selected option on click with using cancel on confirmation box.

这是在点击确认框时使用取消显示已选择选项的最佳方式。

回答by user1063287

Here's a more verbose and commented version of lonesomeday's accepted answer that prompts for confirm on each change and uses .data()rather than jQuery.data().

这是 lonesomeday 接受的答案的更详细和评论版本,提示确认每次更改并使用.data()而不是jQuery.data().

It might help people with understanding the logic a bit more.

它可能会帮助人们更多地理解逻辑。

Accompanying jsFiddle is here.

随附的 jsFiddle 就在这里

// set the initial data value
$(document).ready(function() {
  var my_select = $("#my_select");
  my_select.data("current", "foo");
});

// when selecting another option
$('select').change(function() {
  var $this = $(this);
  var selected = $this.val();

  logit($this, selected, 1); // log data to screen

  // if clicking cancel on the confirm dialog
  if (!confirm('Are you sure?')) {
    logit($this, selected, 2); // log data to screen

    // set the select's value to the stored data value
    var previous_data_value = $(this).data("current");
    $this.val(previous_data_value);
    // escape the onchange function 
    return false;
  }

  // if clicking OK, update the data value to the chosen option
  logit($this, selected, 3); // log data to screen

  $this.data("current", $this.val());

});




// helper functions only below

$(document).on("click", ".clicker", function() {
  var my_select = $("#my_select");
  alert(my_select.data("current"));
});


function logit($this, selected, instance) {
  var current_data_value = $this.data("current");
  if (instance === 1) {
    var value_log = "<span>you selected the value: " + selected + "</span>";
    $(".container_2").append(value_log);
    var data_log = "<span>the previous value was: " + current_data_value + "</span>";
    $(".container_2").append(data_log);
  } else if (instance === 2) {
    $(".container_2").append("<span>you clicked Cancel, value was reverted to: " + current_data_value + "</span>");

  }
  if (instance === 3) {
    $(".container_2").append("<span>you clicked OK, value was changed from '" + current_data_value + "' to '" + selected + "'</span>");
  }

  $(".container_2").append("<span>------------------------------------------------------</span>");
}
* {
  box-sizing: border-box;
}

select {
  width: 200px;
  float: left;
}

.clicker {
  width: 200px;
  float: left;
}

.container_1 {
  margin: auto;
  width: 400px;
  background: lightgray;
  padding-top: 10px;
  padding-bottom: 10px;
}

.container_1:after {
  clear: both;
  content: " ";
  height: 0;
  display: block;
}

.container_2 {
  width: 400px;
  height: 300px;
  overflow-y: auto;
  border: 1px solid gray;
  padding: 10px;
  margin: auto;
  background: #222;
}

span {
  display: block;
  margin-bottom: 5px;
  color: lime;
  font-family: arial;
  font-size: 12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container_1">

  <select id="my_select">
<option value="foo">foo</option>
<option value="bar">bar</option>
<option value="baz">baz</option>
</select>
  <button class="clicker">what's the data value now?</button>
</div>

<div class="container_2">


</div>

回答by sulaiman sudirman

If you are using Select2, you can use something below,

如果您使用的是 Select2,则可以使用以下内容,

$('select').on('select2:selecting', function() {
    if (!confirm('Are you sure you?')) {
         $(this).select2('close')
         return false
    }
})

回答by Tjcool

I think this can be the another way to achieve same.This code will also undo select change.

我认为这可以是实现相同的另一种方法。此代码还将撤消选择更改。

   <div class="selection">

          <input type="radio" class="selected" value="test1" name="test1" 
          checked="checked" /><label>test1</label>

          <input type="radio" name="test1" value="test2" /><label>
          test2</label>

          <input type="radio" name="test1" value="test3" /><label>
          test3</label>

    </div>

     $("input[name='test1']").change(function() {
            var response = confirm("do you want to perform selection change");
            if (response) {
                var container = $(this).closest("div.selection");
                //console.log(container);
                //console.log("old sel =>" + $(container).find(".selected").val());
                $(container).find(".selected").removeClass("selected");
                $(this).addClass("selected");
                //console.log($(this).val());
                console.log("new sel =>" + $(container).find(".selected").val());
            }
            else {
                var container = $(this).closest("div.selection");
                $(this).prop("checked", false);
                $(container).find(".selected").prop("checked", true);
            }
        });

回答by manuxi

Oldschool way (before we used jquery):

老派方式(在我们使用 jquery 之前):

<select id="mySelect" onchange="if(confirm('Do you really want to change?')){ doSomething(); } else { this.selectedIndex=myIndex; }">
    <option value="foo" selected="selected">foo</option>
    <option value="bar">bar</option>
</select>
<script type="text/javascript">
    var myIndex = $('mySelect').selectedIndex;
</script>