首页 文章

HTML表单只读SELECT标签/输入

提问于
浏览
466

根据HTML规范,HTML中的 select 标记没有 readonly 属性,只有 disabled 属性 . 因此,如果您希望阻止用户更改下拉列表,则必须使用 disabled .

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

什么是模拟 select 标签的 readonly 属性的最佳方法,并且仍然获取POST数据?

30 回答

  • 0

    我用jquery解决了它:

    $("select.myselect").bind("focus", function(){
            if($(this).hasClass('readonly'))
            {
              $(this).blur();   
              return;
            }
          });
    
  • 1

    简单地说,在提交表单之前删除disabled属性 .

    $('form').submit(function () {
            $("#Id_Unidade").attr("disabled", false);
        });
    
  • 9

    在IE中,我能够通过双击击败onfocus => onblur方法 . 但记住该值然后在onchange事件中恢复它似乎处理该问题 .

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

    通过使用javascript变量,您可以在没有expando属性的情况下执行类似操作 .

  • 2

    当您计划将其设置为只读时设置禁用选项,然后在提交表单之前删除已禁用的属性 .

    // global variable to store original event/handler for save button
    var form_save_button_func = null;
    
    // function to get jQuery object for save button
    function get_form_button_by_id(button_id) {
        return jQuery("input[type=button]#"+button_id);
    }
    
    // alter value of disabled element
    function set_disabled_elem_value(elem_id, value)  {
        jQuery("#"+elem_id).removeAttr("disabled");
        jQuery("#"+elem_id).val(value);
        jQuery("#"+elem_id).attr('disabled','disabled');
    }
    
    function set_form_bottom_button_save_custom_code_generic(msg) {
        // save original event/handler that was either declared
        // through javascript or html onclick attribute
        // in a global variable
        form_save_button_func = get_form_button_by_id('BtnSave').prop('onclick'); // jQuery 1.6
        //form_save_button_func = get_form_button_by_id('BtnSave').prop('onclick'); // jQuery 1.7
    
        // unbind original event/handler (can use any of following statements below)
        get_form_button_by_value('BtnSave').unbind('click');
        get_form_button_by_value('BtnSave').removeAttr('onclick');
    
        // alternate save code which also calls original event/handler stored in global variable
        get_form_button_by_value('BtnSave').click(function(event){
            event.preventDefault();
            var confirm_result = confirm(msg);
            if (confirm_result) {
                if (jQuery("form.anyForm").find('input[type=text], textarea, select').filter(".disabled-form-elem").length > 0) {
                    jQuery("form.anyForm").find('input[type=text], textarea, select').filter(".disabled-form-elem").removeAttr("disabled");
                }
    
                // disallow further editing of fields once save operation is underway
                // by making them readonly
                // you can also disallow form editing by showing a large transparent
                // div over form such as loading animation with "Saving" message text
                jQuery("form.anyForm").find('input[type=text], textarea, select').attr('ReadOnly','True');
    
                // now execute original event/handler
                form_save_button_func();
            }
        });
    }
    
    $(document).ready(function() {
        // if you want to define save button code in javascript then define it now
    
        // code below for record update
        set_form_bottom_button_save_custom_code_generic("Do you really want to update this record?");
        // code below for new record
        //set_form_bottom_button_save_custom_code_generic("Do you really want to create this new record?");
    
        // start disabling elements on form load by also adding a class to identify disabled elements
        jQuery("input[type=text]#phone").addClass('disabled-form-elem').attr('disabled','disabled');
        jQuery("input[type=text]#fax").addClass('disabled-form-elem').attr('disabled','disabled');
        jQuery("select#country").addClass('disabled-form-elem').attr('disabled','disabled');
        jQuery("textarea#address").addClass('disabled-form-elem').attr('disabled','disabled');
    
        set_disabled_elem_value('phone', '123121231');
        set_disabled_elem_value('fax', '123123123');
        set_disabled_elem_value('country', 'Pakistan');
        set_disabled_elem_value('address', 'address');
    
    }); // end of $(document).ready function
    
  • 19

    另一个更现代的选项(没有双关语)是禁用所选元素之外的所有选项 .

    但请注意,这是一个HTML 4.0功能,即6,7,8 beta 1似乎不尊重这一点 .

    http://www.gtalbot.org/BrowserBugsSection/MSIE7Bugs/OptionDisabledSupport.html

  • 5
    <select id="case_reason" name="case_reason" disabled="disabled">
    

    disabled="disabled" -> 将从数据库中获取您的值,并在表单中显示它 . readonly="readonly" -> 您可以在selectbox中更改您的值,但您的值无法保存在您的数据库中 .

  • 5
    <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和Google Chrome中进行了测试和工作 .

  • 1

    一种简单的服务器端方法是删除除了您要选择的选项之外的所有选项 . 因此,在Zend Framework 1.12中,如果$ element是Zend_Form_Element_Select:

    $value =  $element->getValue();
     $options = $element->getAttrib('options');
     $sole_option = array($value => $options[$value]);
     $element->setAttrib('options', $sole_option);
    
  • 1

    这是最简单和最好的解决方案 . 您将在select或任何其他attr上设置readolny attr,如数据只读,并执行以下操作

    $("select[readonly]").live("focus mousedown mouseup click",function(e){
        e.preventDefault();
        e.stopPropagation();
    });
    
  • 31

    如果选择下拉列表自出生以来是只读的,并且根本不需要更改,那么您可能应该使用另一个控件吗?就像一个简单的 <div> (加上隐藏的表格字段)或 <input type="text">

    Added: 如果下拉列表不是一直只读,并且JavaScript用于启用/禁用它,那么这仍然是一个解决方案 - 只需动态修改DOM即可 .

  • 2

    我通过隐藏选择框并在其位置仅显示信息值来显示 span 来管理它 . 在禁用 .readonly 类的情况下,我们还需要删除 .toVanish 元素并显示 .toShow 元素 .

    $( '.readonly' ).live( 'focus', function(e) {
                    $( this ).attr( 'readonly', 'readonly' )
                    if( $( this ).get(0).tagName == 'SELECT' ) {
                        $( this ).before( '<span class="toVanish readonly" style="border:1px solid; padding:5px">' 
                                + $( this ).find( 'option:selected' ).html() + '</span>' )
                        $( this ).addClass( 'toShow' )
                        $( this ).hide()
                }
        });
    
  • 12

    我知道它已经太晚了,但可以用简单的CSS完成:

    select[readonly] option, select[readonly] optgroup {
        display: none;
    }
    

    当选择处于 readonly 状态时,样式会隐藏所有选项和组,因此用户无法更改其选择 .

    不需要JavaScript hacks .

  • 2

    如果禁用表单字段,则在提交表单时不会发送此字段 . 所以如果你需要 readonly ,它的作用类似于 disabled ,但是发送值会这样做:

    在元素的只读属性发生任何变化之后 .

    $('select.readonly option:not(:selected)').attr('disabled',true);
    
    $('select:not([readonly]) option').removeAttr('disabled');
    
  • 95

    这是我发现的最佳解决方案:

    $("#YourSELECTIdHere option:not(:selected)").prop("disabled", true);
    

    上面的代码 disables 在启用所选选项的情况下未选择所有其他选项 . 这样做所选的选项将使其成为回发后的数据 .

  • 2

    我们也可以用它

    禁用除所选选项以外的所有选项

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

    这样下拉列表仍然有效(并提交其值),但用户无法选择其他值 .

    Demo

  • 43

    简单的jQuery解决方案

    如果您的选择具有 readonly 类,请使用此选项

    jQuery('select.readonly option:not(:selected)').attr('disabled',true);
    

    或者,如果您的选择具有 readonly="readonly" 属性

    $('select[readonly="readonly"] option:not(:selected)').attr('disabled',true);
    
  • 4

    我发现的很好,使用普通的javascript(即:不需要JQuery库),是将 <select> 标签的innerHTML更改为所需的单个剩余值 .

    之前:

    <select name='day' id='day'>
      <option>SUN</option>
      <option>MON</option>
      <option>TUE</option>
      <option>WED</option>
      <option>THU</option>
      <option>FRI</option>
      <option>SAT</option>
    </select>
    

    示例Javascript:

    document.getElementById('day').innerHTML = '<option>FRI</option>';
    

    后:

    <select name='day' id='day'>
      <option>FRI</option>
    </select>
    

    这样,没有任何视觉效果改变,这将在 <FORM> 内POST / GET .

  • 0

    更简单:将style属性添加到 select 标记:

    style="pointer-events: none;"
    
  • 2

    您应该保留 select 元素 disabled ,但也要添加另一个具有相同名称和值的隐藏 input .

    如果重新启用SELECT,则应将其值复制到onchange事件中的隐藏输入,并禁用(或删除)隐藏的输入 .

    这是一个演示:

    $('#mainform').submit(function() {
        $('#formdata_container').show();
        $('#formdata').html($(this).serialize());
        return false;
    });
    
    $('#enableselect').click(function() {
        $('#mainform input[name=animal]')
            .attr("disabled", true);
        
        $('#animal-select')
            .attr('disabled', false)
        	.attr('name', 'animal');
        
        $('#enableselect').hide();
        return false;
    });
    
    #formdata_container {
        padding: 10px;
    }
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div>
        <form id="mainform">
            <select id="animal-select" disabled="true">
                <option value="cat" selected>Cat</option>
                <option value="dog">Dog</option>
                <option value="hamster">Hamster</option>
            </select>
            <input type="hidden" name="animal" value="cat"/>
            <button id="enableselect">Enable</button>
            
            <select name="color">
                <option value="blue" selected>Blue</option>
                <option value="green">Green</option>
                <option value="red">Red</option>
            </select>
    
            <input type="submit"/>
        </form>
    </div>
    
    <div id="formdata_container" style="display:none">
        <div>Submitted data:</div>
        <div id="formdata">
        </div>
    </div>
    
  • 394

    简单的CSS解决方案

    select[readonly]{
        background: #eee;
        cursor:no-drop;
    }
    
    select[readonly] option{
        display:none;
    }
    

    这导致选择为灰色,悬停时带有漂亮的"disable"光标
    并且在选择选项列表时"empty"因此您无法更改其值 .

  • 1

    您可以禁用除当前所选选项之外的所有选项,而不是选择本身 . 这给出了工作下拉列表的外观,但只有您要传入的选项才是有效选择 .

  • 8

    以下为我工作:

    $('select[name=country]').attr("disabled", "disabled");
    
  • 134

    另一种为 select 元素执行 readOnly 属性的方法是使用 css

    你可以这样做:

    $('#selection').css('pointer-events','none');
    

    DEMO

  • 0

    接下来是Grant Wagners的建议;这是一个jQuery代码片段,它使用处理函数而不是直接的onXXX属性来完成它:

    var readonlySelect = function(selector, makeReadonly) {
    
        $(selector).filter("select").each(function(i){
            var select = $(this);
    
            //remove any existing readonly handler
            if(this.readonlyFn) select.unbind("change", this.readonlyFn);
            if(this.readonlyIndex) this.readonlyIndex = null;
    
            if(makeReadonly) {
                this.readonlyIndex = this.selectedIndex;
                this.readonlyFn = function(){
                    this.selectedIndex = this.readonlyIndex;
                };
                select.bind("change", this.readonlyFn);
            }
        });
    
    };
    
  • 5

    HTML解决方案:

    <select onfocus =“this.blur();”>

    javascript:

    selectElement.addEventListener(“focus”,selectElement.blur,true); selectElement.attachEvent(“focus”,selectElement.blur); //谢谢,IE

    去除:

    selectElement.removeEventListener(“focus”,selectElement.blur,true); selectElement.detachEvent(“focus”,selectElement.blur); //谢谢,IE

    编辑:添加删除方法

  • 0

    Solution with 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();
    });
    
  • 5

    这是尝试使用自定义jQuery函数来实现功能(如此处所述):

    $(function(){
    
     $.prototype.toggleDisable = function(flag) {
        // prepare some values
        var selectId = $(this).attr('id');
        var hiddenId = selectId + 'hidden';
        if (flag) {
          // disable the select - however this will not submit the value of the select
          // a new hidden form element will be created below to compensate for the 
          // non-submitted select value 
          $(this).attr('disabled', true);
    
          // gather attributes
          var selectVal = $(this).val();
          var selectName = $(this).attr('name');
    
          // creates a hidden form element to submit the value of the disabled select
          $(this).parents('form').append($('<input></input>').
            attr('type', 'hidden').
            attr('id', hiddenId).
            attr('name', selectName).
            val(selectVal) );
        } else {
          // remove the newly-created hidden form element
          $(this).parents('form').remove(hiddenId);
          // enable back the element
          $(this).removeAttr('disabled');
        }
      }
    
      // Usage
      // $('#some_select_element').toggleDisable(true);
      // $('#some_select_element').toggleDisable(false);
    
    });
    
  • 4

    您可以在提交时重新启用选择对象 .

    EDIT :即,通常禁用select标签(使用disabled属性),然后在提交表单之前自动重新启用它:

    jQuery示例:

    • 要禁用它:
    $('#yourSelect').prop('disabled', true);
    
    • 要在提交之前重新启用它,以便包含GET / POST数据:
    $('#yourForm').on('submit', function() {
        $('#yourSelect').prop('disabled', false);
    });
    

    此外,您可以重新启用每个禁用的输入或选择:

    $('#yourForm').on('submit', function() {
        $('input, select').prop('disabled', false);
    });
    
  • 38

    除了禁用不应该选择的选项之外,我想让它们从列表中消失,但是如果我需要以后仍然可以启用它们:

    $("select[readonly]").find("option:not(:selected)").hide().attr("disabled",true);
    

    这将查找具有readonly属性的所有select元素,然后查找未选中的那些选择内的所有选项,然后隐藏它们并禁用它们 .

    出于性能原因,将jquery查询分成2是很重要的,因为jquery从右到左读取它们,代码如下:

    $("select[readonly] option:not(:selected)")
    

    将首先在文档中找到所有未选中的选项,然后使用readonly属性过滤那些在选择内部的选项 .

  • 0

    如果您正在使用jquery validate,则可以执行以下操作,我使用disabled属性没有问题:

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

相关问题