How to make a specific option unselectable program

2019-06-17 21:41发布

问题:

I have a select with several options and I try to make some of the options unselectable programmatically. For instance, my code is :

<select>
  <option value="1">Value 1</option>
  <option value="2">Value 2</option>
  <option value="3">Value 3</option>
</select>
<script>
  $('select').selectize();
</script>

My question is: how can I make to get option "2" disabled (i.e. not displaying and not selectable) programmatically? -- I tried this code...

$('select')[0].selectize.$dropdown_content.find('[data-value="2"]').removeAttr('data-selectable');

... but it does not work (when I inspect the DOM I see that option "2" has no 'data-selectable' attribute, but it still renders and is selectable...).

Am I wrong here? And if so: what is the proper way to make an option unselectable (I can't find it anywhere in the doc)?

(I created a jsFiddle here: http://jsfiddle.net/j8YUA/3/)

回答1:

You can use the disabledField setting to make a selectize option "unselectable" programmatically when rendering the options. You can also make an option "unselectable" after the fact using the updateOption method (or you can simply remove the option using the removeOption method) For example:

const options = [
  {name: 'Option 1', disable: false},
  {name: 'Option 2', disable: true}
  ];

const sel = $('#select1').selectize({
  options: options,
  valueField: 'name',
  labelField: 'name',
  searchField: ['name'],
  disabledField: 'disable'
});

$('#button1').click(() => {
  sel[0].selectize.updateOption('Option 1', {name: 'Option 1', disable: true});
});

$('#button2').click(() => {
  sel[0].selectize.removeOption('Option 2');
});
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Selectize</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.default.min.css">
  </head>

  <body>

    <div>Option 2 disabled</div>
    <input id="select1" name="select1" type="text" />
    <button id="button1">Disable Option 1</button>
    <button id="button2">Remove Option 2</button>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.js"></script>

  </body>

</html>



回答2:

Selectize options are stored in object $('select')[0].selectize.options, so to delete an option you should delete respective property from options object

 delete $('select')[0].selectize.options["2"];