How to make a dropdown readonly using jquery?

后端 未结 21 1188
终归单人心
终归单人心 2020-12-02 06:54

I am using the following statement to make it readonly but it is not working.

$(\'#cf_1268591\').attr(\"readonly\", \"readonly\"); 

I don\

21条回答
  •  没有蜡笔的小新
    2020-12-02 07:46

    Setting an element with disabled will not submit the data, however select elements don't have readonly.

    You can simulate a readonly on select using CSS for styling and JS to prevent change with tab:

    select[readonly] {
      background: #eee;
      pointer-events: none;
      touch-action: none;
    }
    

    Then use it like:

    var readonly_select = $('select');
    $(readonly_select).attr('readonly', true).attr('data-original-value', $(readonly_select).val()).on('change', function(i) {
        $(i.target).val($(this).attr('data-original-value'));
    });
    

    Result:

      // Updated 08/2018 to prevent changing value with tab
    $('a').on('click', function() {
    var readonly_select = $('select');
    $(readonly_select).attr('readonly', true).attr('data-original-value', $(readonly_select).val()).on('change', function(i) {
    	$(i.target).val($(this).attr('data-original-value'));
    });
    });
    select[readonly] {
      background: #eee;
      pointer-events: none;
      touch-action: none;
    }
    
    Click here to enable readonly
    

提交回复
热议问题