如果现有选项中没有一个与使用javascript存在的特定字符串匹配,则向下拉列表添加新选项

如果现有选项中没有一个与使用javascript存在的特定字符串匹配,则向下拉列表添加新选项,javascript,arrays,Javascript,Arrays,我有一个下拉列表,可以与数组进行比较。如果数组中的某个值与下拉列表中某个选项的文本匹配,则选中该值: JS-第一步: var topicArray = ['Apples', 'Tomatoes']; populateExistingDropDowns ('topicSelect',topicArray); 下拉列表 <select class="topicSelect" multiple> <optgroup label="Crops"> <

我有一个下拉列表,可以与数组进行比较。如果数组中的某个值与下拉列表中某个选项的文本匹配,则选中该值:

JS-第一步:

var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns ('topicSelect',topicArray);
下拉列表

<select class="topicSelect" multiple>
    <optgroup label="Crops">
        <option selected="" value=""></option>
        <option value="Apiculture">Apiculture</option>
        <option value="Apples">Apples</option>
        <option value="Aquaculture">Aquaculture</option>
        <option value="Blueberries">Blueberries</option>
    </optgroup>
    <optgroup label="Add Option" class="youOwn">
        <option value="own">Add Your Option</option>
    </optgroup>
</select>

养蜂业
苹果
水产养殖
蓝莓
添加您的选项
JS-第二步:

function populateExistingDropDowns(dd, array) {
    var select = document.getElementsByClassName(dd);
    for (var d = 0; d < array.length; d++) {
        for (var i = 0; i < select[0].options.length; i += 1) {
            if (select[0].options[i].text === array[d]) {
                select[0].options[i].selected = true;
            }
        }
    }
}
函数填充现有下拉列表(dd,数组){
var select=document.getElementsByClassName(dd);
对于(var d=0;d
我的问题来了:上面显示的代码工作得很好,但是如果不存在具有相同数组值的选项,我希望能够添加一个新选项。在上面显示的示例中,数组中有两个值(“苹果”和“西红柿”)。当我遍历数组和下拉列表时,选择了“苹果”选项,但是,我如何才能添加新的“西红柿”选项,然后再选择它?提前感谢,如果需要更多详细信息,请告诉我

如果不存在具有相同数组值的选项,我希望能够添加一个新选项

您可以克隆一个选项节点,修改它并将其附加到父节点

在代码片段中,我添加了一个专用函数

函数填充现有下拉列表(dd,数组){
var select=document.getElementsByClassName(dd);
外部:
对于(var d=0;d

养蜂业
苹果
水产养殖
蓝莓
添加您的选项
如果不存在具有相同数组值的选项,我希望能够添加一个新选项

您可以克隆一个选项节点,修改它并将其附加到父节点

在代码片段中,我添加了一个专用函数

函数填充现有下拉列表(dd,数组){
var select=document.getElementsByClassName(dd);
外部:
对于(var d=0;d

养蜂业
苹果
水产养殖
蓝莓
添加您的选项

使用ES6语法的一种方法如下:

function populateExistingDropDowns(dd, array) {

  // using 'let' rather than 'var' to declare variables,
  // using document.querySelector(), rather than
  // getElementsByClassName(), because d.qS has support
  // in IE8 (whereas it does not support
  // getElementsByClassName()); however here we get the
  // first element that matches the selector:
  let dropdown = document.querySelector('.' + dd),

    // retrieving the collection of option elements,
    // HTMLSelectElement.options, and converting that
    // collection into an Array using Array.from():
    options = Array.from(dropdown.options);

  // iterating over each of the topics in the passed-in
  // array, using Array.prototype.forEach():
  array.forEach(function(topic) {

    // filtering the array of <option> elements to keep
    // only those whose text property is equal to the
    // current topic (from the array):
    let opts = options.filter(opt => topic === opt.text);

    // if the opts Array has a truthy non-zero length:
    if (opts.length) {

      // we iterate over the returned filtered Array
      // and, using Arrow function syntax, set each
      // node's selected property to true:
      opts.forEach(opt => opt.selected = true);
    } else {

      // otherwise, if the current topic returned no
      // <option> elements, we find the <optgroup>
      // holding the 'Crops' and append a new Child
      // using Node.appendChild(), and the new Option()
      // constructor to set the option-text, option-value
      // default-selected property and selected property:
      dropdown.querySelector('optgroup[label=Crops]')
        .appendChild(new Option(topic, topic, true, true));
    }
  });
}

var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns('topicSelect', topicArray);

养蜂业
苹果
水产养殖
蓝莓
添加您的选项

使用ES6语法的一种方法如下:

function populateExistingDropDowns(dd, array) {

  // using 'let' rather than 'var' to declare variables,
  // using document.querySelector(), rather than
  // getElementsByClassName(), because d.qS has support
  // in IE8 (whereas it does not support
  // getElementsByClassName()); however here we get the
  // first element that matches the selector:
  let dropdown = document.querySelector('.' + dd),

    // retrieving the collection of option elements,
    // HTMLSelectElement.options, and converting that
    // collection into an Array using Array.from():
    options = Array.from(dropdown.options);

  // iterating over each of the topics in the passed-in
  // array, using Array.prototype.forEach():
  array.forEach(function(topic) {

    // filtering the array of <option> elements to keep
    // only those whose text property is equal to the
    // current topic (from the array):
    let opts = options.filter(opt => topic === opt.text);

    // if the opts Array has a truthy non-zero length:
    if (opts.length) {

      // we iterate over the returned filtered Array
      // and, using Arrow function syntax, set each
      // node's selected property to true:
      opts.forEach(opt => opt.selected = true);
    } else {

      // otherwise, if the current topic returned no
      // <option> elements, we find the <optgroup>
      // holding the 'Crops' and append a new Child
      // using Node.appendChild(), and the new Option()
      // constructor to set the option-text, option-value
      // default-selected property and selected property:
      dropdown.querySelector('optgroup[label=Crops]')
        .appendChild(new Option(topic, topic, true, true));
    }
  });
}

var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns('topicSelect', topicArray);

养蜂业
苹果
水产养殖
蓝莓
添加您的选项

谢谢所有回答我问题的人。我最后用了这个:

function populateExistingDropDowns(dd, array) {
var select = document.getElementsByClassName(dd);
var opt = document.createElement('option');
 for (var d = 0; d < array.length; d++) {
  for (var q = 0; q < select[0].length; q++) {
   if (select[0].options[q].text !== array[d]) {
    opt.value = array[d];
    opt.text = array[d];
    select[0].children[1].appendChild(opt);
    opt.selected = true;
     } else {
    select[0].options[q].selected = true;
           }
      }
     }
   }
函数填充现有下拉列表(dd,数组){
var select=document.getElementsByClassName(dd);
var opt=document.createElement('option');
对于(var d=0;d

谢谢所有回答我问题的人。我最后用了这个:

function populateExistingDropDowns(dd, array) {
var select = document.getElementsByClassName(dd);
var opt = document.createElement('option');
 for (var d = 0; d < array.length; d++) {
  for (var q = 0; q < select[0].length; q++) {
   if (select[0].options[q].text !== array[d]) {
    opt.value = array[d];
    opt.text = array[d];
    select[0].children[1].appendChild(opt);
    opt.selected = true;
     } else {
    select[0].options[q].selected = true;
           }
      }
     }
   }
函数填充现有下拉列表(dd,数组){
var select=document.getElementsByClassName(dd);
var opt=document.createElement('option');
对于(var d=0;d

您是否尝试过拼接?您是否尝试在下拉列表中选择多个选项?@VijendraKulhade,multiselect会很好,因为我可能会在不同的下拉列表中重复使用此选项,尽管我不需要它用于此特定情况。您是否尝试过拼接?您是否尝试在下拉列表中选择多个选项?@VijendraKulhade,multiselect会很好很好,因为我可以在不同的下拉列表中重复使用它,尽管我不需要在这个特定的情况下使用它