Knowledgebase Home Page  >  RapidSpell Web ASP.NET  >  Behavior Customization
Search the Knowledge Base
Combobox and as-you-type support with jQuery.
https://keyoti.com/kb/Default.aspx?ToDo=view&questId=280&catId=55

Options

Print this page
Email this to a friend

There is a jQuery UI example where a HTML select element is turned into a combobox, using the .autocomplete widget.  With some modifications this can also be adapted to work with RapidSpell and be as you type enabled.

 

Below are the modified jquery.combobox.js script and an example HTML page that uses it.

 

jquery.combobox.js

 

(function( $ ) {

      $.widget( "ui.combobox", {

            _create:

                  function()

                  {

                        if( this.element.width() < 68 )

                              this.element.width("68px");

                       

                        this.element.prop("multiple", false);

                        var wrapperWidth = parseInt(this.element.css("width"));

                        this.wrapper = $( "<span>" )

                        .addClass( "ui-combobox" )

                        .css({"width" : wrapperWidth + "px"})

                        .insertAfter( this.element );

 

                        $(".ui-autocomplete").css({"width":this.element.width(),"left":"none","top":"0px","position":"fixed"});

                        this.element.hide();

                        this._createAutocomplete();

                        this._createShowAllButton();

                        if( this.element.prop("disabled") )

                              this.disable();

                  },

 

            _createAutocomplete:

                  function()

                  {

                        var element = this.element;

                        var selected = this.element.children( ":selected" );

                        var value = selected.val() ? selected.text().trim() : "";

                        var id = this.element.prop("id") + "_combobox_input";

                       

                        if( $("#" + this.element.prop("id")).val() == "" || $("#" + this.element.prop("id")).val() == null || $("#" + this.element.prop("id")).val() == "null" || $("#" + this.element.prop("id") + " option:selected").text().trim() == "Select")

                              value = "";

                       

                        var inputWidth = parseInt(this.element.css("width").replace("px","")) - 27;

                        /*keyoti this.input = $( "<input>" )

                        .appendTo( this.wrapper )

                        .val( value )

                        .prop( "tabIndex", this.element.prop("tabIndex") )

                        .prop( "title", "" )

                        .prop( "id", id )

                        .prop( "placeholder", "Select a value")

                        .prop( "maxlength", "512")*/

                        this.input = $('#'+id)

                        .addClass( "ui-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )

                        .css({ "width": inputWidth + "px", "height": "16px", "background": "#FFF" })

                      ;//keyoti

               

                        this.input.on('keyup', function (e) {

                            var ifID = this.id + "_IF";

                            var menuItemCount = $('#' + ifID).autocomplete('widget').menu()[0].children.length;

 

                            if (e.keyCode == 40) {//DOWN

                                var ev = $.Event('keydown');

                                ev.which = 40;

 

                                autocomplete_workaround_active_item = 1 + (autocomplete_workaround_active_item % menuItemCount);

                                $('#' + ifID).autocomplete('widget').menu('focus', null, $('#' + ifID).autocomplete('widget').menu().find(".ui-menu-item:nth-child(" + autocomplete_workaround_active_item + ")"));

                                cancelBubble(e);

                            } else if (e.keyCode == 38) {//DOWN

                                var ev = $.Event('keydown');

                                ev.which = 38;

 

                                if (autocomplete_workaround_active_item-- == 0) autocomplete_workaround_active_item = menuItemCount;

                                $('#' + ifID).autocomplete('widget').menu('focus', null, $('#' + ifID).autocomplete('widget').menu().find(".ui-menu-item:nth-child(" + autocomplete_workaround_active_item + ")"));

                                cancelBubble(e);

                            } else if (e.keyCode == 13) {//ENTER

                                var ev = $.Event('keydown');

                                ev.which = 13;

                                ev.target = $('#' + ifID).autocomplete('widget').menu().find(".ui-menu-item:nth-child(" + autocomplete_workaround_active_item + ")");

                                $('#' + ifID).autocomplete('widget').menu('select', ev);

                                cancelBubble(e);

                            } else {

                              

                                $('#' + ifID).autocomplete('search', this.value);

                            }

                        });

 

           

 

                      $('#' + id+"_IF")

                        .autocomplete({

                              delay: 0,

                              minLength: 0,

                              source: $.proxy( this, "_source" ),

                              open: function (event, ui) {

                                    var menu = $(this).data("uiAutocomplete").menu

                                          , i = 0

                                          , $items = $('li', menu.element)

                                          , item

                                          , text

                                          , startsWith = new RegExp("^" + this.value, "i");

                                   

                                    for (; i < $items.length && !item; i++) {

                                          text = $items.eq(i).text().trim();

                                          if (startsWith.test(text)) {

                                                item = $items.eq(i);

                                          }

                                    }

                                   

                                    if (item) {

                                          menu.focus(null, item);

                                    }

                              },//KEYOTI

                              select: function (event, ui) {

 

                                  //rsw_getTBSFromID(id, false).setContent(ui.item.value);

                                  $('#' + id).val(ui.item.value);

                                  rsw_getTBSFromID(id, false).updateIframe();

                              }

                        })

                        .bind({

                            click: function () {

                                $("#" + id + "_a").click();

                            },

                              keypress: function (e) {

                                    var vRestrictedChars = [34, 35, 38, 39, 92, 220, 222];

                                    var k = e.which;

                                    if ((vRestrictedChars.indexOf(k) >= 0))

                                    {

                                          if(e.preventDefault)

                                                e.preventDefault();

                                          else

                                                e.returnValue = false;

                                    }

                              },

                              copy: function () {

                                 // $('span').text('copy behaviour detected!');

                              },

                              paste: function () {

                                    var self = $(this);

                                    var orig = self.val();

                                    setTimeout(function () {

                                          var pasted = $(self).val();

                                          var outputString = pasted.trim().replace(/[#\\'"&]+/gi, '');

                                          $(self).prop("value", "" + outputString);

                                    });

                              },

                              cut: function () {

                                 // $('span').text('cut behaviour detected!');

                              },

                              drop: function(event, ui) {

                                    event.stopPropagation();

                                    event.preventDefault();

                              }

                        })

                        .tooltip({

                              tooltipClass: "ui-state-highlight"

                        });

                        var input = this.input;

                        var val = "";

                        this.input_hid = $( "<input type='hidden'>" )

                        .appendTo( this.wrapper ).prop( "id", id + "_Hid" )

                        .val( value ).css({"width": "1px","display":"none"});

                        this.input_val_hid = $( "<input type='hidden'>" )

                        .appendTo( this.wrapper ).prop( "id", id + "Val_Hid" )

                        .val( value ).css({"width": "1px","display":"none"});

                       

                        this._on( this.input, {

                              autocompleteselect:

                                    function( event, ui ) {

                                          val = ui.item.option.text.trim();

                                          ui.item.option.selected = true;

                                          this._trigger( "select", event, {

                                                item: ui.item.option

                                          });

                                          if( this.input.val() != this.input_hid.val() || this.input.val() != val || this.input_val_hid != ui.item.option.value)

                                          {

                                                this.input_hid.prop("value", this.element.children( ":selected" ).text().trim());

                                                this.input_val_hid.prop("value", this.element.children( ":selected" ).val());

                                                setTimeout(function(){

                                                                  if( $("#" + element.prop("id")).val() == "" || $("#" + element.prop("id")).val() == null || $("#" + element.prop("id")).val() == "null" || $("#" + element.prop("id") + " option:selected").text().trim() == "Select" || $("#" + id + " option:selected").text().trim() == " ")

                                                                        input.prop("value", "");

                                                                  else

                                                                        input.prop("value", val);

                                                                  element.change();

                                                                  }, 20);

                                          }

                                    },

                              autocompletechange: "_removeIfInvalid"

                        });

                  },

 

            _createShowAllButton:

                  function()

                  {

                      //KEYOTI var input = this.input,

                      var input = $('#' + this.input[0].id+'_IF'),

                        wasOpen = false;

                        var id = input.prop("id") + "_a";

                        this.button = $( "<input type='button'>" )

                        .prop( "tabIndex", -1 )

                        .prop( "id", id )

                        .tooltip()

                        .appendTo( this.wrapper )

                        .addClass( "ui-combobox-toggle ui-corner-right ui-state-default ui-widget ui-icon ui-button" ).css("backgroundPosition", "-62px -14px").css("height", "20px")

                        .removeClass( "ui-corner-all" )

                        .mousedown(function() {

                              wasOpen = input.autocomplete( "widget" ).is( ":visible" );

                        })

                        .click(

                              function(){

                                    wasOpen = input.autocomplete( "widget" ).is( ":visible" );

                                    //KEYOTI input.focus();

                                    // Close if already visible

                                    if ( wasOpen ) {

                                          return;

                                    }

                                    // Pass empty string as value to search for, displaying all results

                                    input.autocomplete( "search", "" );

                              }

                        )

                  },

 

            _source:

                  function( request, response )

                  {

                        this.element.click();

                        var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );

                        var input = this.input;

                        response( this.element.children( "option" ).map(function() {

                              var text  = $( this ).text().trim();

                              var value = $( this ).val();

                              var title = $( this ).prop("title");

                              var disable = $( this ).prop("disabled");

                              if ( this.value && (!request.term || matcher.test(text) ) )

                                    return {label: text, value: text, title: title, rel : input.val(), disabled : disable, option: this};

                        }));

                  },

           

            _removeIfInvalid: function( event, ui ) {

                  // Selected an item, nothing to do

                  if ( ui.item )

                  {

                        //this.element.change();

                        return;

                  }

                

                  // Search for a match (case-insensitive)

                  var value = trim(this.input.val()),

                    valueLowerCase = value.toLowerCase(),

                    valid = false;

                  this.element.children( "option" ).each(function() {

                    if ( $( this ).text().trim().toLowerCase() === valueLowerCase ) {

                        this.selected = valid = true;

                        return false;

                    }

                    else if ( valueLowerCase == "" && $( this ).val().toLowerCase() === valueLowerCase ) {

                        this.selected = valid = true;

                        return false;

                    }

                  });

                 

//                if( !valid && trim(this.input.val()) == "" && ($("#" + this.element.prop("id") options[0]).val() == "" || document.getElementById(this.element.prop("id")).options[0].text == ) )

                  /*Need to do some R&D on 20150915 by DN

                  if( !valid && trim(this.input.val()) == "" && ($("#" + this.element.prop("id")+" options[0]").val() == "" || $("#" + this.element.prop("id")+" options[0]").text() == "") )

                  {

                        valid = true;

                        this.element.prop("value", "");

                        if( this.element.val() == null )

                              this.element.prop("value", "0");

                  }

                 */

                  // Found a match, nothing to do

                  if ( valid ) {

                        this.element.change();

                        if( $("#" + this.element.prop("id")).val() == "" || $("#" + this.element.prop("id")).val() == null || $("#" + this.element.prop("id")).val() == "null" || $("#" + this.element.prop("id") + " option:selected").text().trim() == "Select")

                              this.input.prop("value", "");

                        else

                              this.input.prop("value", this.element.children( ":selected" ).text().trim());

 

                        this.input_hid.prop("value", this.input.val());

                        //if( this.input.val() != "" )

                              this.input_val_hid.prop("value", this.element.children( ":selected" ).val());

                        //else

                              //this.input_val_hid.prop("value", "");

                        return;

                  }

     

                  // Remove invalid value

                  this.input

                    .val( "" )

                    .attr( "title", value + " didn't match any item" )

                    .tooltip( "open" );

                  //this.element.val( "" );

                  //this.element.prop("selectedIndex", 0);

                  //this.element.change();

                  this._delay(function() {

                    this.input.tooltip( "close" ).attr( "title", "" );

                    this.refresh();

                  }, 2500 );

                  this.input.autocomplete( "instance" ).term = "";

              },

                 

            _destroy:

                  function()

                  {

                        //console.log("Combo Box Destroy");

                        this.wrapper.remove();

                        this.element.show();

                  },

                 

            enable:

                  function()

                  {

                        //console.log("Combo Box Enable");

                        if( this.input.prop("disabled") )

                        {

                              var input   = this.input,

                                    wasOpen = false;

                              this.element.prop("disabled", false);

                              this.input.prop("disabled", false).removeClass("ui-state-disabled").css({"background":"#FFF"});

                              var vAnchorID = this.input.prop("id");

                              $("#" + vAnchorID + "_a").bind("click", function(){

                                                                                                      wasOpen = input.autocomplete( "widget" ).is( ":visible" );

                                                                                                      input.focus();

                                                                                                      // Close if already visible

                                                                                                      if ( wasOpen ) {

                                                                                                            return;

                                                                                                      }

                                                                                                      // Pass empty string as value to search for, displaying all results

                                                                                                      input.autocomplete( "search", "" );

                                                                                                      }).prop({disabled:false}).removeClass("ui-state-disabled");

                        }

                  },

     

            disable:

                  function()

                  {

                        //console.log("Combo Box Disable");

                        this.element.prop("disabled", true);

                        this.input.prop("disabled", true).addClass("ui-state-disabled");

                        var vAnchorID = this.input.prop("id");

                        $("#" + vAnchorID + "_a").unbind("click").prop({disabled:true}).addClass("ui-state-disabled");

                  },

                 

            refresh:

                  function()

                  {

                        //console.log("Combo Box Refresh");

                        var id = this.element.prop("id");

                        if( $("#" + id).val() == "" || $("#" + id).val() == null || $("#" + id).val() == "null" || $("#" + id + " option:selected").text().trim() == "Select" || $("#" + id + " option:selected").text().trim() == " ")

                              this.input.prop("value" , "");

                        else

                              this.input.prop("value" , $("#" + id + " option:selected").text().trim());

                       

                        this.input_hid.prop("value", this.input.val());

                        //if( this.input.val() != "" )

                              this.input_val_hid.prop("value", this.element.children( ":selected" ).val());

                        //else

                              //this.input_val_hid.prop("value", "");

                        this._trigger('refresh');

                  },

                 

            mandatory:

                  function()

                  {

                        //console.log("Combo Box Mandatory");

                        this.input.css("backgroundColor" , "#FFF");

                        this.input.prop("value" , trim(this.input.val()));

                        if( this.input.val() == "" || this.input.val().length == 0 || $("#" + this.element.prop("id")).val() == "" || $("#" + this.element.prop("id")).val() == null || $("#" + this.element.prop("id")).val() == "null" || $("#" + this.element.prop("id") + " option:selected").text().trim() == "Select")

                        {

                              this.input.css("backgroundColor" , "#FF9999");

                              //alert("Please select an option from available list");

                              this.input

                                .attr( "title", "Please select an option from available list" )

                                .tooltip( "open" );

                              this._delay(function() {

                                this.input.tooltip( "close" ).attr( "title", "" );

                                this.refresh();

                              }, 2500 );

                              this.input.focus();

                              return false;

                        }

                        return true;

                  },

                 

            error:

                  function()

                  {

                        //console.log("Combo Box Error");

                        this.input.css("backgroundColor" , "#FF9999");

                        this.input.focus();

                        return false;

                  },

           

            changeBgc:

                  function()

                  {

                        //console.log("Combo Box Error");

                        this.input.css("backgroundColor" , "#FFFFFF");

                  },

      });

})( jQuery );

 

 

 

 

 

Example HTML file

 

 

<!doctype html>

<html lang="en">

<head>

  <meta charset="utf-8">

  <title>jQuery UI Autocomplete - Default functionality</title>

  <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">

 <!--cdn-->

  <script src="//code.jquery.com/jquery-1.10.2.js"></script>

  <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

 

 

  <script src="/Scripts/jquery.combobox.js"></script>

  <link rel="stylesheet" href="/resources/demos/style.css">

  <script src="/Scripts/RapidSpell-AYT.js" type="text/javascript"></script>

  <script type="text/javascript">

                

        var autocomplete_Onload = window.onload;

        var autocompleter;

        var autocomplete_workaround_active_item = 0;

        window.onload = function () {

            if (typeof (autocomplete_Onload) == 'function') autocomplete_Onload();

                var v = $("#testing_cb").combobox();

                $(":text").css("height", "20px");

               

        };

  </script>

</head>

<body>

    <form>

        <div style="padding:15px;">

          

            <input id='testing_cb_combobox_input' placeholder='select a value'    />

            <select name="testing_cb" id="testing_cb" style="width:210px;">

                <option value="1">1</option>

                <option value="10">10</option>

                <option value="100">100</option>

                <option value="1000">1000</option>

                <option value="10000">10000</option>

            </select>

        </div>

    </form>

</body>

</html>

 

 

Please modify the path to jquery.combobox.js and RapidSpell-AYT.js in the script tags, accordingly.

Related Questions:

Attachments:

No attachments were found.