How to make a dropdown readonly using jquery?

后端 未结 21 1038
终归单人心
终归单人心 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

    This is what you are looking for:

    $('#cf_1268591').attr("style", "pointer-events: none;");
    

    Works like a charm.

    0 讨论(0)
  • 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;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="#">Click here to enable readonly</a>
    <select>
    <option>Example 1</option>
    <option selected>Example 2</option>
    <option>Example 3</option>
    </select>

    0 讨论(0)
  • 2020-12-02 07:46

    You could also disable it and at the moment that you make the submit call enable it. I think is the easiest way :)

    0 讨论(0)
提交回复
热议问题