根据HTML规范,HTML中的select标签没有readonly属性,只有disabled属性。所以如果你想让用户不改变下拉菜单,你必须使用disabled。

唯一的问题是禁用的HTML表单输入不会包含在POST / get数据中。

什么是最好的方法来模拟一个选择标签的只读属性,仍然得到POST数据?


当前回答

使用tabindex解决方案。适用于选择和文本输入。

简单地使用.disabled类。

CSS:

.disabled {
    pointer-events:none; /* No cursor */
    background-color: #eee; /* Gray background */
}

JS:

$(".disabled").attr("tabindex", "-1");

HTML:

<select class="disabled">
    <option value="0">0</option>
</select>

<input type="text" class="disabled" />

编辑:使用Internet Explorer,你还需要这个JS:

$(document).on("mousedown", ".disabled", function (e) {
    e.preventDefault();
});

其他回答

<select id="countries" onfocus="this.defaultIndex=this.selectedIndex;" onchange="this.selectedIndex=this.defaultIndex;">
<option value="1">Country1</option>
<option value="2">Country2</option>
<option value="3">Country3</option>
<option value="4">Country4</option>
<option value="5">Country5</option>
<option value="6">Country6</option>
<option value="7" selected="selected">Country7</option>
<option value="8">Country8</option>
<option value="9">Country9</option>
</select>

测试和工作在IE 6, 7和8b2, Firefox 2和3,Opera 9.62, Safari 3.2.1 for Windows和谷歌Chrome。

“选择多个”对上述代码建议的响应几乎没有那么好。经过大量的推敲和拼凑,我最终得到了这个:

var thisId="";
var thisVal="";
function selectAll(){
    $("#"+thisId+" option").each(function(){
        if(!$(this).prop("disabled"))$(this).prop("selected",true);
    });
    $("#"+thisId).prop("disabled",false);
}
$(document).ready(function(){
    $("select option:not(:selected)").attr('disabled',true);
    $("select[multiple]").focus(function(){
        thisId=$(this).prop("id");
        thisVal=$(this).val();
        $(this).prop("disabled",true).blur();
        setTimeout("selectAll();",200);
    });
});

如果你正在使用jquery验证,你可以做下面的事情,我使用disabled属性没有问题:

$(function(){
    $('#myform').validate({
        submitHandler:function(form){
            $('select').removeAttr('disabled');
            form.submit();
        }
    });
});

html的解决方案:

<选择聚焦事件= " this.blur ();" >

javascript的:

selectElement。addEventListener(“焦点”,selectElement。模糊,真正的); selectElement。attachEvent(“焦点”,selectElement.blur);/ /谢谢,IE

删除:

selectElement。removeEventListener(“焦点”,selectElement。模糊,真正的); selectElement.detachEvent(“焦点”,selectElement.blur);/ /谢谢,IE

编辑:增加删除方法

在IE中,我可以通过双击来击败onfocus=>onblur方法。 但是记住值,然后在onchange事件中恢复它似乎可以解决这个问题。

<select onfocus="this.oldvalue=this.value;this.blur();" onchange="this.value=this.oldvalue;">
....
</select>

你可以使用javascript变量来做类似的事情,而不需要expando属性。