Javascript jQuery 防止更改选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5426387/
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-23 17:09:33  来源:igfitidea点击:

jQuery prevent change for select

javascriptjqueryeventsselect

提问by overgroove

I want to prevent a select box from being changed if a certain condition applies. Doing this doesn't seem to work:

如果某个条件适用,我想防止选择框被更改。这样做似乎不起作用:

$('#my_select').bind('change', function(ev) {
  if(my_condition)
  {
    ev.preventDefault();
    return false;
  }
});

I'm guessing this is because by this point the selected option has already changed.

我猜这是因为此时所选的选项已经更改。

What are other ways of doing this?

还有什么其他方法可以做到这一点?

采纳答案by mattsven

Try this:

尝试这个:

http://jsfiddle.net/qk2Pc/

http://jsfiddle.net/qk2Pc/

var my_condition = true;
var lastSel = $("#my_select option:selected");

$("#my_select").change(function(){
  if(my_condition)
  {
    lastSel.prop("selected", true);
  }
});

$("#my_select").click(function(){
    lastSel = $("#my_select option:selected");
});

回答by dwallace

In the event someone needs a generic version of mattsven's answer (as I did), here it is:

如果有人需要 mattsven 答案的通用版本(就像我一样),这里是:

$('select').each(function() {
    $(this).data('lastSelected', $(this).find('option:selected'));
});

$('select').change(function() {
    if(my_condition) {
        $(this).data('lastSelected').attr('selected', true);
    }
});

$('select').click(function() {
    $(this).data('lastSelected', $(this).find('option:selected'));
});

回答by Chris Longmoon

If you simply want to prevent interaction with the select altogether when my_condition is true, you could always just capture the mousedown event and do your event prevent there:

如果您只是想在 my_condition 为真时完全阻止与 select 交互,您可以随时捕获 mousedown 事件并在那里阻止您的事件:

var my_condition = true;

$("#my_select").mousedown(function(e){
  if(my_condition)
  {
     e.preventDefault();
     alert("Because my_condition is true, you cannot make this change.");
  }
});

This will prevent any change event from ever occurring while my_condition is true.

这将防止在 my_condition 为真时发生任何更改事件。

回答by Rion Williams

Another option to consider is disabling it when you do not want it to be able to be changed and enabling it:

另一个要考虑的选项是当您不希望它能够被更改并启用它时禁用它:

//When select should be disabled:
{
    $('#my_select').attr('disabled', 'disabled');
}

//When select should not be disabled
{
    $('#my_select').removeAttr('disabled');
}

Update since your comment (if I understand the functionality you want):

自您发表评论后更新(如果我了解您想要的功能):

$("#dropdown").change(function()
{
    var answer = confirm("Are you sure you want to change your selection?")
    {
        if(answer)
        {
            //Update dropdown (Perform update logic)
        }
        else
        {
            //Allow Change (Do nothing - allow change)
        } 
    }            
}); 

Demo

演示

回答by user2125504

None of the answers worked well for me. The easy solution in my case was:

没有一个答案对我有用。在我的情况下,简单的解决方案是:

$("#selectToNotAllow").focus(function(e) {
    $("#someOtherTextfield").focus();
});

This accomplishes clicking or tabbing to the select drop down and simply moves the focus to a different field (a nearby text input that was set to readonly) when attempting to focus on the select. May sound like silly trickery, but very effective.

这完成了单击或切换到选择下拉菜单,并在尝试聚焦选择时将焦点移动到不同的字段(设置为只读的附近文本输入)。可能听起来像愚蠢的诡计,但非常有效。

回答by Giolvani

You can do this without jquery...

你可以在没有 jquery 的情况下做到这一点......

<select onchange="event.target.selectedIndex = 0">
...
</select>

or you can do a function to check your condition

或者你可以做一个功能来检查你的状况

<select onchange="check(event)">
...
</select>

<script>
function check(e){
    if (my_condition){
        event.target.selectedIndex = 0;
    }
}
</script>

回答by Karthik Moorthy

Implement custom readonly like eventHandler

像 eventHandler 一样实现自定义只读

<select id='country' data-changeable=false>
  <option selected value="INDIA">India</option>
  <option value="USA">United States</option>
  <option value="UK">United Kingdom</option>
</select>

<script>
    var lastSelected = $("#country option:selected");

    $("#country").on("change", function() {
       if(!$(this).data(changeable)) {
            lastSelected.attr("selected", true);              
       }        
    });

    $("#country").on("click", function() {
       lastSelected = $("#country option:selected");
    });
</script>

Demo : https://jsfiddle.net/0mvajuay/8/

演示:https: //jsfiddle.net/0mvajuay/8/

回答by w.stoettinger

This was the ONLY thing that worked for me (on Chrome Version 54.0.2840.27):

这是唯一对我有用的东西(在 Chrome 版本 54.0.2840.27 上):

$('select').each(function() {
  $(this).data('lastSelectedIndex', this.selectedIndex);
});
$('select').click(function() {
  $(this).data('lastSelectedIndex', this.selectedIndex);
});

$('select[class*="select-with-confirm"]').change(function() {  
  if (!confirm("Do you really want to change?")) {
    this.selectedIndex = $(this).data('lastSelectedIndex');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id='fruits' class="select-with-confirm">
  <option selected value="apples">Apples</option>
  <option value="bananas">Bananas</option>
  <option value="melons">Melons</option>
</select>

<select id='people'>
  <option selected value="john">John</option>
  <option value="Hyman">Hyman</option>
  <option value="jane">Jane</option>
</select>

回答by Patrick from NDepend team

This worked for me, no need to keep a lastSelectedif you know the optionIndexto select.

这对我有用,lastSelected如果您知道optionIndex要选择,则无需保留。

var optionIndex = ...
$(this)[0].options[optionIndex].selected = true;

回答by Morteza Soltanabadiyan

$('#my_select').bind('mousedown', function (event) {
         event.preventDefault();
         event.stopImmediatePropagation();
     });