最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add new item in dropdown - Stack Overflow

programmeradmin1浏览0评论

I want to add option(Add new item) if data not found while searching data in drop-down.

I tried a lot but didn't got the actual output.

For reference you can see the example.

(function($){

  // a case insensitive jQuery :contains selector
  $.expr[":"].searchableSelectContains = $.expr.createPseudo(function(arg) {
    return function( elem ) {
      return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
  });

  $.searchableSelect = function(element, options) {
    this.element = element;
    this.options = options;
    this.init();

    var _this = this;

    this.searchableElement.click(function(event){
      // event.stopPropagation();
      _this.show();
    }).on('keydown', function(event){
      if (event.which === 13 || event.which === 40 || event.which == 38){
        event.preventDefault();
        _this.show();
      }
    });

    $(document).on('click', null, function(event){
      if(_this.searchableElement.has($(event.target)).length === 0)
        _this.hide();
    });

    this.input.on('keydown', function(event){
      event.stopPropagation();
      if(event.which === 13){         //enter
        event.preventDefault();
        _this.selectCurrentHoverItem();
        _this.hide();
      } else if (event.which == 27) { //ese
        _this.hide();
      } else if (event.which == 40) { //down
        _this.hoverNextItem();
      } else if (event.which == 38) { //up
        _this.hoverPreviousItem();
      }
    }).on('keyup', function(event){
      if(event.which != 13 && event.which != 27 && event.which != 38 && event.which != 40)
        _this.filter();
    })
  }

  var $sS = $.searchableSelect;

  $sS.fn = $sS.prototype = {
    version: '0.0.1'
  };

  $sS.fn.extend = $sS.extend = $.extend;

  $sS.fn.extend({
    init: function(){
      var _this = this;
      this.element.hide();

      this.searchableElement = $('<div tabindex="0" class="searchable-select"></div>');
      this.holder = $('<div class="searchable-select-holder"></div>');
      this.dropdown = $('<div class="searchable-select-dropdown searchable-select-hide"></div>');
      this.input = $('<input type="text" class="searchable-select-input" />');
      this.items = $('<div class="searchable-select-items"></div>');
      this.caret = $('<span class="searchable-select-caret"></span>');

      this.dropdown.append(this.input);
      this.dropdown.append(this.items);
      this.searchableElement.append(this.caret);
      this.searchableElement.append(this.holder);
      this.searchableElement.append(this.dropdown);
      this.element.after(this.searchableElement);

      this.buildItems();
    },

    filter: function(){
      var text = this.input.val();
      this.items.find('.searchable-select-item').addClass('searchable-select-hide');
      this.items.find('.searchable-select-item:searchableSelectContains('+text+')').removeClass('searchable-select-hide');
      if(this.currentSelectedItem.hasClass('searchable-select-hide') && this.items.find('.searchable-select-item:not(.searchable-select-hide)').length > 0){
        this.hoverFirstNotHideItem();
      }
    },

    hoverFirstNotHideItem: function(){
      this.hoverItem(this.items.find('.searchable-select-item:not(.searchable-select-hide)').first());
    },

    selectCurrentHoverItem: function(){
      if(!this.currentHoverItem.hasClass('searchable-select-hide'))
        this.selectItem(this.currentHoverItem);
    },

    hoverPreviousItem: function(){
      if(!this.hasCurrentHoverItem())
        this.hoverFirstNotHideItem();
      else{
        var prevItem = this.currentHoverItem.prevAll('.searchable-select-item:not(.searchable-select-hide):first')
        if(prevItem.length > 0)
          this.hoverItem(prevItem);
      }
    },

    hoverNextItem: function(){
      if(!this.hasCurrentHoverItem())
        this.hoverFirstNotHideItem();
      else{
        var nextItem = this.currentHoverItem.nextAll('.searchable-select-item:not(.searchable-select-hide):first')
        if(nextItem.length > 0)
          this.hoverItem(nextItem);
      }
    },

    buildItems: function(){
      var _this = this;
      this.element.find('option').each(function(){
        var item = $('<div class="searchable-select-item" data-value="'+$(this).attr('value')+'">'+$(this).text()+'</div>');

        if(this.selected){
          _this.selectItem(item);
          _this.hoverItem(item);
        }

        item.on('mouseenter', function(){
          $(this).addClass('hover');
        }).on('mouseleave', function(){
          $(this).removeClass('hover');
        }).click(function(event){
          event.stopPropagation();
          _this.selectItem($(this));
          _this.hide();
        });

        _this.items.append(item);
      });
    },
    show: function(){
      this.dropdown.removeClass('searchable-select-hide');
      this.input.focus();
      this.status = 'show';
    },

    hide: function(){
      if(!(this.status === 'show'))
        return;

      if(this.items.find(':not(.searchable-select-hide)').length === 0)
          this.input.val('');
      this.dropdown.addClass('searchable-select-hide');
      this.searchableElement.trigger('focus');
      this.status = 'hide';
    },

    hasCurrentSelectedItem: function(){
      return this.currentSelectedItem && this.currentSelectedItem.length > 0;
    },

    selectItem: function(item){
      if(this.hasCurrentSelectedItem())
        this.currentSelectedItem.removeClass('selected');

      this.currentSelectedItem = item;
      item.addClass('selected');

      this.hoverItem(item);

      this.holder.text(item.text());
      var value = item.data('value');
      this.holder.data('value', value);
      this.element.val(value);
    },

    hasCurrentHoverItem: function(){
      return this.currentHoverItem && this.currentHoverItem.length > 0;
    },

    hoverItem: function(item){
      if(this.hasCurrentHoverItem())
        this.currentHoverItem.removeClass('hover');

      if(item.outerHeight() + item.position().top > this.items.height())
        this.items.scrollTop(this.items.scrollTop() + item.outerHeight() + item.position().top - this.items.height());
      else if(item.position().top < 0)
        this.items.scrollTop(this.items.scrollTop() + item.position().top);

      this.currentHoverItem = item;
      item.addClass('hover');
    }
  });

  $.fn.searchableSelect = function(options){
    this.each(function(){
      var sS = new $sS($(this), options);
    });

    return this;
  };

})(jQuery);
.searchable-select-hide {
  display: none;
}

.searchable-select {
  display: inline-block;
  min-width: 200px;
  font-size: 14px;
  line-height: 1.428571429;
  color: #555;
  vertical-align: middle;
  position: relative;
  /*outline: none;*/
}

.searchable-select-holder{
  padding: 6px;
  background-color: #fff;
  background-image: none;
  border: 1px solid #ccc;
  border-radius: 4px;
  -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
  box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
  -webkit-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
  transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
}

.searchable-select-caret {
  position: absolute;
  width: 0;
  height: 0;
  box-sizing: border-box;
  border-color: black transparent transparent transparent;
  top: 0;
  bottom: 0;
  border-style: solid;
  border-width: 5px;
  margin: auto;
  right: 10px;
}

.searchable-select-dropdown {
  position: absolute;
  background-color: #fff;
  border: 1px solid #ccc;
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
  padding: 4px;
  border-top: none;
  top: 28px;
  left: 0;
  right: 0;
}

.searchable-select-input {
  margin-top: 5px;
  border: 1px solid #ccc;
  outline: none;
  padding: 4px;
  width: 100%;
  box-sizing: border-box;
  width: 100%;
}

.searchable-select-items {
  margin-top: 4px;
  max-height: 400px;
  overflow-y: scroll;
  position: relative;
}

.searchable-select-items::-webkit-scrollbar {
  display: none;
}

.searchable-select-item {
  padding: 5px 5px;
  cursor: pointer;
}

.searchable-select-item.hover {
  background: #555;
  color: white;
}

.searchable-select-item.selected {
  background: #28a4c9;
  color: white;
}
<script src=".1.1/jquery.min.js"></script>
<body>
    <select>
      <option value="Personalize">Personalize</option>
      <option value="BlackBerry">BlackBerry</option>
      <option value="device">device</option>
      <option value="with">with</option>
      <option value="entertainment">entertainment</option>
      <option value="and">and</option>
      <option value="social">social</option>
      <option value="networking">networking</option>
      <option value="apps">apps</option>
      <option value="or">or</option>
      <option value="apps">apps</option>
      <option value="that">that</option>
      <option value="will">will</option>
      <option value="boost">boost</option>
      <option value="your">your</option>        
      <option value="productivity">productivity</option>
      <option value="Download">Download</option>
      <option value="or">or</option>
      <option value="buy">buy</option>
      <option value="apps">apps</option>
      <option value="from">from</option>
      <option value="Afbb">Afbb</option>
      <option value="Akademie">Akademie</option>
      <option value="Berlin">Berlin</option>
      <option value="reviews">reviews</option>
      <option value="by">by</option>
      <option value="real">real</option>
    </select>
    <script>$(function(){$('select').searchableSelect();});</script>
  </body>

I want to add option(Add new item) if data not found while searching data in drop-down.

I tried a lot but didn't got the actual output.

For reference you can see the example.

(function($){

  // a case insensitive jQuery :contains selector
  $.expr[":"].searchableSelectContains = $.expr.createPseudo(function(arg) {
    return function( elem ) {
      return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
  });

  $.searchableSelect = function(element, options) {
    this.element = element;
    this.options = options;
    this.init();

    var _this = this;

    this.searchableElement.click(function(event){
      // event.stopPropagation();
      _this.show();
    }).on('keydown', function(event){
      if (event.which === 13 || event.which === 40 || event.which == 38){
        event.preventDefault();
        _this.show();
      }
    });

    $(document).on('click', null, function(event){
      if(_this.searchableElement.has($(event.target)).length === 0)
        _this.hide();
    });

    this.input.on('keydown', function(event){
      event.stopPropagation();
      if(event.which === 13){         //enter
        event.preventDefault();
        _this.selectCurrentHoverItem();
        _this.hide();
      } else if (event.which == 27) { //ese
        _this.hide();
      } else if (event.which == 40) { //down
        _this.hoverNextItem();
      } else if (event.which == 38) { //up
        _this.hoverPreviousItem();
      }
    }).on('keyup', function(event){
      if(event.which != 13 && event.which != 27 && event.which != 38 && event.which != 40)
        _this.filter();
    })
  }

  var $sS = $.searchableSelect;

  $sS.fn = $sS.prototype = {
    version: '0.0.1'
  };

  $sS.fn.extend = $sS.extend = $.extend;

  $sS.fn.extend({
    init: function(){
      var _this = this;
      this.element.hide();

      this.searchableElement = $('<div tabindex="0" class="searchable-select"></div>');
      this.holder = $('<div class="searchable-select-holder"></div>');
      this.dropdown = $('<div class="searchable-select-dropdown searchable-select-hide"></div>');
      this.input = $('<input type="text" class="searchable-select-input" />');
      this.items = $('<div class="searchable-select-items"></div>');
      this.caret = $('<span class="searchable-select-caret"></span>');

      this.dropdown.append(this.input);
      this.dropdown.append(this.items);
      this.searchableElement.append(this.caret);
      this.searchableElement.append(this.holder);
      this.searchableElement.append(this.dropdown);
      this.element.after(this.searchableElement);

      this.buildItems();
    },

    filter: function(){
      var text = this.input.val();
      this.items.find('.searchable-select-item').addClass('searchable-select-hide');
      this.items.find('.searchable-select-item:searchableSelectContains('+text+')').removeClass('searchable-select-hide');
      if(this.currentSelectedItem.hasClass('searchable-select-hide') && this.items.find('.searchable-select-item:not(.searchable-select-hide)').length > 0){
        this.hoverFirstNotHideItem();
      }
    },

    hoverFirstNotHideItem: function(){
      this.hoverItem(this.items.find('.searchable-select-item:not(.searchable-select-hide)').first());
    },

    selectCurrentHoverItem: function(){
      if(!this.currentHoverItem.hasClass('searchable-select-hide'))
        this.selectItem(this.currentHoverItem);
    },

    hoverPreviousItem: function(){
      if(!this.hasCurrentHoverItem())
        this.hoverFirstNotHideItem();
      else{
        var prevItem = this.currentHoverItem.prevAll('.searchable-select-item:not(.searchable-select-hide):first')
        if(prevItem.length > 0)
          this.hoverItem(prevItem);
      }
    },

    hoverNextItem: function(){
      if(!this.hasCurrentHoverItem())
        this.hoverFirstNotHideItem();
      else{
        var nextItem = this.currentHoverItem.nextAll('.searchable-select-item:not(.searchable-select-hide):first')
        if(nextItem.length > 0)
          this.hoverItem(nextItem);
      }
    },

    buildItems: function(){
      var _this = this;
      this.element.find('option').each(function(){
        var item = $('<div class="searchable-select-item" data-value="'+$(this).attr('value')+'">'+$(this).text()+'</div>');

        if(this.selected){
          _this.selectItem(item);
          _this.hoverItem(item);
        }

        item.on('mouseenter', function(){
          $(this).addClass('hover');
        }).on('mouseleave', function(){
          $(this).removeClass('hover');
        }).click(function(event){
          event.stopPropagation();
          _this.selectItem($(this));
          _this.hide();
        });

        _this.items.append(item);
      });
    },
    show: function(){
      this.dropdown.removeClass('searchable-select-hide');
      this.input.focus();
      this.status = 'show';
    },

    hide: function(){
      if(!(this.status === 'show'))
        return;

      if(this.items.find(':not(.searchable-select-hide)').length === 0)
          this.input.val('');
      this.dropdown.addClass('searchable-select-hide');
      this.searchableElement.trigger('focus');
      this.status = 'hide';
    },

    hasCurrentSelectedItem: function(){
      return this.currentSelectedItem && this.currentSelectedItem.length > 0;
    },

    selectItem: function(item){
      if(this.hasCurrentSelectedItem())
        this.currentSelectedItem.removeClass('selected');

      this.currentSelectedItem = item;
      item.addClass('selected');

      this.hoverItem(item);

      this.holder.text(item.text());
      var value = item.data('value');
      this.holder.data('value', value);
      this.element.val(value);
    },

    hasCurrentHoverItem: function(){
      return this.currentHoverItem && this.currentHoverItem.length > 0;
    },

    hoverItem: function(item){
      if(this.hasCurrentHoverItem())
        this.currentHoverItem.removeClass('hover');

      if(item.outerHeight() + item.position().top > this.items.height())
        this.items.scrollTop(this.items.scrollTop() + item.outerHeight() + item.position().top - this.items.height());
      else if(item.position().top < 0)
        this.items.scrollTop(this.items.scrollTop() + item.position().top);

      this.currentHoverItem = item;
      item.addClass('hover');
    }
  });

  $.fn.searchableSelect = function(options){
    this.each(function(){
      var sS = new $sS($(this), options);
    });

    return this;
  };

})(jQuery);
.searchable-select-hide {
  display: none;
}

.searchable-select {
  display: inline-block;
  min-width: 200px;
  font-size: 14px;
  line-height: 1.428571429;
  color: #555;
  vertical-align: middle;
  position: relative;
  /*outline: none;*/
}

.searchable-select-holder{
  padding: 6px;
  background-color: #fff;
  background-image: none;
  border: 1px solid #ccc;
  border-radius: 4px;
  -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
  box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
  -webkit-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
  transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
}

.searchable-select-caret {
  position: absolute;
  width: 0;
  height: 0;
  box-sizing: border-box;
  border-color: black transparent transparent transparent;
  top: 0;
  bottom: 0;
  border-style: solid;
  border-width: 5px;
  margin: auto;
  right: 10px;
}

.searchable-select-dropdown {
  position: absolute;
  background-color: #fff;
  border: 1px solid #ccc;
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
  padding: 4px;
  border-top: none;
  top: 28px;
  left: 0;
  right: 0;
}

.searchable-select-input {
  margin-top: 5px;
  border: 1px solid #ccc;
  outline: none;
  padding: 4px;
  width: 100%;
  box-sizing: border-box;
  width: 100%;
}

.searchable-select-items {
  margin-top: 4px;
  max-height: 400px;
  overflow-y: scroll;
  position: relative;
}

.searchable-select-items::-webkit-scrollbar {
  display: none;
}

.searchable-select-item {
  padding: 5px 5px;
  cursor: pointer;
}

.searchable-select-item.hover {
  background: #555;
  color: white;
}

.searchable-select-item.selected {
  background: #28a4c9;
  color: white;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <select>
      <option value="Personalize">Personalize</option>
      <option value="BlackBerry">BlackBerry</option>
      <option value="device">device</option>
      <option value="with">with</option>
      <option value="entertainment">entertainment</option>
      <option value="and">and</option>
      <option value="social">social</option>
      <option value="networking">networking</option>
      <option value="apps">apps</option>
      <option value="or">or</option>
      <option value="apps">apps</option>
      <option value="that">that</option>
      <option value="will">will</option>
      <option value="boost">boost</option>
      <option value="your">your</option>        
      <option value="productivity">productivity</option>
      <option value="Download">Download</option>
      <option value="or">or</option>
      <option value="buy">buy</option>
      <option value="apps">apps</option>
      <option value="from">from</option>
      <option value="Afbb">Afbb</option>
      <option value="Akademie">Akademie</option>
      <option value="Berlin">Berlin</option>
      <option value="reviews">reviews</option>
      <option value="by">by</option>
      <option value="real">real</option>
    </select>
    <script>$(function(){$('select').searchableSelect();});</script>
  </body>

Share Improve this question edited Jun 26, 2015 at 12:33 Jainik Patel 2,3441 gold badge18 silver badges38 bronze badges asked Jun 26, 2015 at 12:22 harshharsh 971 silver badge7 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 1

I'm currently having the same problem. But why don't you use the Selectivity JS (https://arendjr.github.io/selectivity/)? It's quite flexible and easy in use.

On the webpage there are some examples. In my program I used it like this: there is a dropdown-list with options. If user prints something, but the option is not found, it still can be added to the multiple choice. There is the function createTokenItem - Function to create a new item from a user's search term, but I haven't understood yet how to implement it.

Anyway here's the piece of my code:

In html:

<div id="multipleSelect"></div>

In js file:

$('#multipleSelect').selectivity({
           multiple: true,
           inputType: "Email",
           items: ["192.168.93.114:8181", "192.168.93.115:8181", "192.168.93.116:8181"],
           placeholder: 'Choose servers',
           showDropdown: true
    });
$("#multipleSelect").on("change", function(){
        var total =  $('#multipleSelect').selectivity("value");
        //Do something
    });

You can also load items in another way, like not writing them all, but download as an array of Objects in format {"id": id, "text": "text"}. Id - optionally

Add new item in dropdown:

function AddItem(selectBox, name, value)
{
    var newOption = document.createElement("option");
    newOption.text = name;
    newOption.value = value;
    selectBox.add(newOption);
}

You can try This Code

<HTML xmlns="http://www.w3/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/HTML; charset=iso-8859-1" />
        <title>Add Option Items </title>
        <script type="text/javaScript">
            function addNewListItem(){
                var htmlSelect=document.getElementById('selectYear');
                var optionValue=document.getElementById('txtYearValue');
                var optionDisplaytext=document.getElementById('txtYearDisplayValue');

                if(optionValue.value==''||isNaN(optionValue.value)){
                    alert('please enter option value');
                    optionValue.focus();
                    return false;
                }
                if(optionDisplaytext.value==''||isNaN(optionDisplaytext.value)){
                    alert('please enter option display text');
                    optionDisplaytext.focus();
                    return false;
                }
                if(isOptionAlreadyExist(htmlSelect,optionValue.value)){
                    alert('Option value already exists');
                    optionValue.focus();
                    return false;
                }
                if(isOptionAlreadyExist(htmlSelect,optionDisplaytext.value)){
                    alert('Display text already exists');
                    optionDisplaytext.focus();
                    return false;
                }
                var selectBoxOption = document.createElement("option");
                selectBoxOption.value = optionValue.value;
                selectBoxOption.text = optionDisplaytext.value;
                htmlSelect.add(selectBoxOption, null); 
                alert("Option has been added successfully");
                return true;

            }
            function isOptionAlreadyExist(listBox,value){
                var exists=false;
                for(var x=0;x<listBox.options.length;x++){
                    if(listBox.options[x].value==value || listBox.options[x].text==value){ 
                        exists=true;
                        break;
                    }
                }
                return exists;
            }
        </script>
    </head>

    <body>
        <table border="0" align="left">
            <tr>
                <td align="right">Year</td>
                <td align="left"><select name="selectYear" id="selectYear">
                    <option value="2000">2000</option>
                    <option value="2001">2001</option>
                    <option value="2002">2002</option>
                    <option value="2003">2003</option>
                    <option value="2004">2004</option>
                </select></td>
            </tr>
            <tr>
                <td align="right">Option Value</td>
                <td align="left"><input name="txtYearValue" type="text" id="txtYearValue" /></td>
            </tr>
            <tr>
                <td align="right">Option Display Text</td>
                <td align="left"><input name="txtYearDisplayValue" type="text" id="txtYearDisplayValue" /></td>
            </tr>
            <tr>
                <td align="right">&nbsp;</td>
                <td align="left"><input name="btnAddItem" type="button" id="btnAddItem" value="Add Option" onclick="javaScript:addNewListItem();" /></td>
            </tr>
        </table>
    </body>
</HTML>

if you any problem then Refers This link

Hi you can use select2 which is inspired by chosen but way more flexible! Check out the Link of Examples Go to the Tagging support section..

发布评论

评论列表(0)

  1. 暂无评论