Select2 - make it readonly (not disabled!) from js

主宰稳场 提交于 2019-12-06 18:37:49

问题


How can I dynamically make a select2 combobox read-only?

Here's what I've tried so far:

$('...').attr({'readonly': 'readonly'}).trigger('change.select2');
$('...').attr({'readonly': 'readonly'}).trigger('change');
$('...').select2().enable(false);

回答1:


See: http://select2.github.io/select2/

I did it with:

$("#modelname-fieldname").select2({disabled:readonly});

Where:

  • modelname-fieldname is as in: $form -> field($modelname, "fieldname") -> widget(Select2::classname(), [ ... ]);
  • readonly is true, false or a string readonly

Optionally you can change the cursor when hovering over the select2 field.




回答2:


This is Solution for Latest select2 (Tested With 4.0.7) using css only

/*Select2 ReadOnly Start*/
    select[readonly].select2-hidden-accessible + .select2-container {
        pointer-events: none;
        touch-action: none;
    }

    select[readonly].select2-hidden-accessible + .select2-container .select2-selection {
        background: #eee;
        box-shadow: none;
    }

    select[readonly].select2-hidden-accessible + .select2-container .select2-selection__arrow, select[readonly].select2-hidden-accessible + .select2-container .select2-selection__clear {
        display: none;
    }

/*Select2 ReadOnly End*/



回答3:


Solution from Select2 - Issue #3387 - Readonly Support:

select[readonly].select2 + .select2-container {
  pointer-events: none;
  touch-action: none;

  .select2-selection {
    background: #eee;
    box-shadow: none;
  }

  .select2-selection__arrow,
  .select2-selection__clear {
    display: none;
  }
}

Edit: for versions > 4.07 - as commenters below correctly pointed out:

select[readonly].select2-hidden-accessible + .select2-container {
    pointer-events: none;
    touch-action: none;

    .select2-selection {
        background: #eee;
        box-shadow: none;
    }

    .select2-selection__arrow, select[readonly].select2-hidden-accessible + .select2-container .select2-selection__clear {
        display: none;
    }
}


来源:https://stackoverflow.com/questions/41807096/select2-make-it-readonly-not-disabled-from-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!