使用Javascript / JQuery动态更新选择字段

时间:2018-07-24 06:38:43

标签: javascript jquery selectize.js

我有一个包含许多字段的表单,其中包括一些使用Selectize jquery插件的选择。表单所做的部分工作涉及从模式窗口中获取输入,然后将其动态添加到相关的“选定”选择字段中。

我目前正在执行以下操作:

//Initialise Selectize on the required fields
var $select = $('.selectize').selectize(...do some stuff in here...);

//Fetch the selectize instances
var select0 = $select[0].selectize;
var select1 = $select[1].selectize;
...etc, one for each select...

//This is where I get the text entered in the modal and update 
//the relevant select field.
function processText(){  

  //Get the name of the field we need to update  
  var thisFormElement = $('#sourceFormElementName').val();
  //Get the text to update the above field with
  var thisText = $('#inputQuickTextOriginalText').val();

  //Figure out which select field to update. Messy.
  if(thisFormElement == "select0"){
    //'select#' is the reference back to the selectize instances we declared earlier
    select0.addOption({value:thisText, text:thisText});
    select0.addItem(thisText);          
  }     
  else if(thisFormElement == "select1"){
    select1.addOption({value:thisText, text:thisText});
    select1.addItem(thisText);          
  }
  ...more statements...
}

大概一种清除方法是使用thisFormElement值(或类似值)引用selectize实例。这样就无需添加if语句,并且无需更改代码的这一部分即可添加新字段。例如。像这样:

//Assume thisFormElement = select0, for example
var thisFormElement = $('#sourceFormElementName').val();

thisFormElement.addOption({value:thisText, text:thisText});
thisFormElement.addItem(thisText);          

我知道上述方法不起作用,但是有什么方法可以实现类似的目的(或者完全是完全不同的方式)?

1 个答案:

答案 0 :(得分:0)

以下是一种使用户能够在一个字段中输入选项并将该选项添加到相应的selectize字段的方法。对于只需要基本功能使用户能够将新选项添加​​到选择字段的用户,请查看Tagging demo from the selectize documentation

const params = {
  options: [],
  placeholder: 'Select...',
  valueField: 'value',
  labelField: 'text',
  searchField: ['text'],
  create: false
};

// init selectize inputs and add to 'selects' array
const selects = [];
selects.push($('#select1').selectize(params));
selects.push($('#select2').selectize(params));

$('#add button').click(() => {
  $('#add input').each((index, elem) => {
    if (elem.value) {
      let id = $(elem).data('select-id');
      for (let select of selects) {
        // find corresponding selectize field and add option
        if (id === select[0].id) {
          let value = Object.keys(select[0].selectize.options).length + 1;
          let text = elem.value;
          select[0].selectize.addOption({value: value, text: text});
          select[0].selectize.addItem(value);
          break;
        }
      }
    }
  });
});
<!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 id="add">
      <div>
        <input name="add1" type="text" value="" placeholder="Add option to 1st select..." data-select-id="select1" />
      </div>
      <div>
        <input name="add2" type="text" value="" placeholder="Add option to 2nd select..." data-select-id="select2" />
      </div>
      <div>
        <button>Add</button>
      </div>
    </div>
    
    <br>
    
    <form id="select" action="" method="POST">
      <input class="myselect" id="select1" name="select1" type="text" />
      <input class="myselect" id="select2" name="select2" type="text" />
    </form>
    
    <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>