Javascript HTML 选择元素的只读等效项

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

A readOnly Equivalent for HTML Select Elements

javascripthtmldomprototypejs

提问by Alan Storm

Is there an attribute or technique for HTML select fields that's equivalent to readOnly="true"for HTML inputs?

HTML 选择字段是否有与readOnly="true"HTML 输入等效的属性或技术 ?

I have an form select field I'd like to disable, but still pass on when the form is posted. If this were an HTML input, I'd do something like this

我有一个我想禁用的表单选择字段,但在表单发布时仍然传递。如果这是一个 HTML 输入,我会做这样的事情

$('select_id').setAttribute('readOnly', 'true');

and the browser would render the field as un-editable, but it's value would still be passed to the backend. I'd like something similar for an HTML select, but doing the following

并且浏览器会将字段呈现为不可编辑,但它的值仍会传递给后端。我想要类似的 HTML 选择,但执行以下操作

$('#select_id').setAttribute('readOnly', 'true');

doesn't work. The attribute is successfully added to the DOM, but the browser still renders it as selectable.

不起作用。该属性已成功添加到 DOM,但浏览器仍将其呈现为可选。

I realize I could do the following

我意识到我可以做到以下几点

$('#input_id').disabled();

but when a field is disabledits value isn't passed through to the backend.

但是当一个字段被禁用时,它的值不会传递到后端。

I'd like a way to disable this select field but still pass in on to the backend.

我想要一种禁用此选择字段但仍传递到后端的方法。

(examples use Prototype JS, but I'm interested in any general solution)

(示例使用 Prototype JS,但我对任何通用解决方案感兴趣)

回答by Sjoerd

Disable all but the selected option:

禁用除所选选项之外的所有选项:

?

?

<select>
<option disabled="disabled">1</option>
<option selected="selected">2</option>
<option disabled="disabled">3</option>
</select>

This way the dropdown still works (and submits its value) but the user can not select another value.

这样下拉菜单仍然有效(并提交其值),但用户无法选择另一个值。

回答by Anonymous

add disabled class:

添加禁用类:

.disabled{
   color: grey;
}

if class present use prevent default on focus and on click, and dbl click:

如果存在类,则使用阻止默认的焦点和点击,以及 dbl 点击:

$('#el').bind('click dblclick focus').function(event){
   if ($(this).hasClass('disabled')) event.preventDefault();
});