如果某个条件适用,我想防止选择框被更改。这样做似乎不起作用:
$('#my_select').bind('change', function(ev) {
if(my_condition)
{
ev.preventDefault();
return false;
}
});
我猜这是因为此时所选的选项已经更改。
还有什么其他方法可以做到这一点?
如果某个条件适用,我想防止选择框被更改。这样做似乎不起作用:
$('#my_select').bind('change', function(ev) {
if(my_condition)
{
ev.preventDefault();
return false;
}
});
我猜这是因为此时所选的选项已经更改。
还有什么其他方法可以做到这一点?
试试这个:
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");
});
如果有人需要 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'));
});
如果您只是想在 my_condition 为真时完全阻止与选择的交互,您可以随时捕获 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.");
}
});
这将防止在 my_condition 为真时发生任何更改事件。
另一个要考虑的选项是在您不希望它被更改时禁用它并启用它:
//When select should be disabled:
{
$('#my_select').attr('disabled', 'disabled');
}
//When select should not be disabled
{
$('#my_select').removeAttr('disabled');
}
自您发表评论后更新(如果我了解您想要的功能):
$("#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)
}
}
});
没有一个答案对我有用。在我的情况下,简单的解决方案是:
$("#selectToNotAllow").focus(function(e) {
$("#someOtherTextfield").focus();
});
这完成了单击或切换到选择下拉菜单,并在尝试聚焦选择时将焦点移动到不同的字段(附近设置为只读的文本输入)。可能听起来像愚蠢的诡计,但非常有效。