How to work with jQuery autocomplete?

Asked

Viewed 282 times

2

I’m using autocomplete from jQuery, but I’m having the following problem:

In the first line of <select> I’d like the famous to appear "Escolha abaixo uma opção"

<option value="">Escolha abaixo uma opção</option>

Or, in the case of editing, value of the <select> from the bank.

But nothing I do works, only a blank line appears.

Obs.: The autocoplete works normal. The <select> normal population with data coming from the database. The problem is only the first line of the <select>.

I created the script below that technically should fill the first line of <select>.

$stringClientes = "";

if($Clientes == null)   {
    $stringClientes .= "<option value=''>Ainda não existe Cliente cadastrado</option>";
}
else {
    $ClienteCadastro = $ClientesDao->pesquisaClienteEdicao($_GET["idClienteCadastro"]);

    if(isset($_GET["idClienteCadastro"]) && $ClienteCadastro != null) {     
        $stringClientes .= "<option value='".$ClienteCadastro->getIdClientes()."'>".$ClienteCadastro->getNome()."</option>";        
    } else {
        $stringClientes .= '<option value="">Escolha um cliente abaixo</option>';
    }
    
    foreach ($Clientes as $cliente) {
        $stringClientes .= "<option value='".$cliente->getIdClientes()."'>".$cliente->getNome()."</option>";
    }
}

And, in the <select>

  <div>
        <label>Cliente</label>
        <select name="cliente" id="cliente" required>
            <option value="" selected>Selecione</option>
             <?php echo $stringClientes; ?>
        </select><br /> <br /> 
  </div>

In time. The variable, $stringClientes, brings correctly to the <select> all the <option>s, including the first line. But it seems that autocomplete does not allow us to put text in the combobox.

The full return of select comes out like this:

<select name="cliente" id="cliente" required>
    <option value="" selected>Selecione</option>
    <option value='17'>José das couves</option>
    <option value='14'>Fulano de Tal</option>
    <option value='15'>tal fulano</option>
    <option value='16'>Antônio Bandeiras</option>
    <option value='17'>José das couves</option>
</select>

But the first line: <option value="" selected>Selecione</option> doesn’t come out!

In that case I thought popular the type['text'] with the value "" or what comes from the bank. How to fill this type['text'] that is only in the plugin?

  • Now I get it! Is that the autocomplete did not accept value="". I put value="#" and it worked!

2 answers

0

With the example of the site, it works perfectly and does what you want At this link

Example here

Select

<div class="ui-widget">
  <label>Your preferred programming language: </label>
  <select id="combobox">
    <option value="">Select one...</option>
    <option value="ActionScript">ActionScript</option>
    <option value="AppleScript">AppleScript</option>

  </select>
</div>

Full example of the website:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Autocomplete - Combobox</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">
  <style>
  .custom-combobox {
    position: relative;
    display: inline-block;
  }
  .custom-combobox-toggle {
    position: absolute;
    top: 0;
    bottom: 0;
    margin-left: -1px;
    padding: 0;
  }
  .custom-combobox-input {
    margin: 0;
    padding: 5px 10px;
  }
  </style>
  <script>
  (function( $ ) {
    $.widget( "custom.combobox", {
      _create: function() {
        this.wrapper = $( "<span>" )
          .addClass( "custom-combobox" )
          .insertAfter( this.element );

        this.element.hide();
        this._createAutocomplete();
        this._createShowAllButton();
      },

      _createAutocomplete: function() {
        var selected = this.element.children( ":selected" ),
          value = selected.val() ? selected.text() : "";

        this.input = $( "<input>" )
          .appendTo( this.wrapper )
          .val( value )
          .attr( "title", "" )
          .addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
          .autocomplete({
            delay: 0,
            minLength: 0,
            source: $.proxy( this, "_source" )
          })
          .tooltip({
            tooltipClass: "ui-state-highlight"
          });

        this._on( this.input, {
          autocompleteselect: function( event, ui ) {
            ui.item.option.selected = true;
            this._trigger( "select", event, {
              item: ui.item.option
            });
          },

          autocompletechange: "_removeIfInvalid"
        });
      },

      _createShowAllButton: function() {
        var input = this.input,
          wasOpen = false;

        $( "<a>" )
          .attr( "tabIndex", -1 )
          .attr( "title", "Show All Items" )
          .tooltip()
          .appendTo( this.wrapper )
          .button({
            icons: {
              primary: "ui-icon-triangle-1-s"
            },
            text: false
          })
          .removeClass( "ui-corner-all" )
          .addClass( "custom-combobox-toggle ui-corner-right" )
          .mousedown(function() {
            wasOpen = input.autocomplete( "widget" ).is( ":visible" );
          })
          .click(function() {
            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 ) {
        var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
        response( this.element.children( "option" ).map(function() {
          var text = $( this ).text();
          if ( this.value && ( !request.term || matcher.test(text) ) )
            return {
              label: text,
              value: text,
              option: this
            };
        }) );
      },

      _removeIfInvalid: function( event, ui ) {

        // Selected an item, nothing to do
        if ( ui.item ) {
          return;
        }

        // Search for a match (case-insensitive)
        var value = this.input.val(),
          valueLowerCase = value.toLowerCase(),
          valid = false;
        this.element.children( "option" ).each(function() {
          if ( $( this ).text().toLowerCase() === valueLowerCase ) {
            this.selected = valid = true;
            return false;
          }
        });

        // Found a match, nothing to do
        if ( valid ) {
          return;
        }

        // Remove invalid value
        this.input
          .val( "" )
          .attr( "title", value + " didn't match any item" )
          .tooltip( "open" );
        this.element.val( "" );
        this._delay(function() {
          this.input.tooltip( "close" ).attr( "title", "" );
        }, 2500 );
        this.input.autocomplete( "instance" ).term = "";
      },

      _destroy: function() {
        this.wrapper.remove();
        this.element.show();
      }
    });
  })( jQuery );

  $(function() {
    $( "#combobox" ).combobox();
    $( "#toggle" ).click(function() {
      $( "#combobox" ).toggle();
    });
  });
  </script>
</head>
<body>

<div class="ui-widget">
  <label>Your preferred programming language: </label>
  <select id="combobox">
    <option value="">Select one...</option>
    <option value="ActionScript">ActionScript</option>
    <option value="AppleScript">AppleScript</option>
    <option value="Asp">Asp</option>
    <option value="BASIC">BASIC</option>
    <option value="C">C</option>
    <option value="C++">C++</option>
    <option value="Clojure">Clojure</option>
    <option value="COBOL">COBOL</option>
    <option value="ColdFusion">ColdFusion</option>
    <option value="Erlang">Erlang</option>
    <option value="Fortran">Fortran</option>
    <option value="Groovy">Groovy</option>
    <option value="Haskell">Haskell</option>
    <option value="Java">Java</option>
    <option value="JavaScript">JavaScript</option>
    <option value="Lisp">Lisp</option>
    <option value="Perl">Perl</option>
    <option value="PHP">PHP</option>
    <option value="Python">Python</option>
    <option value="Ruby">Ruby</option>
    <option value="Scala">Scala</option>
    <option value="Scheme">Scheme</option>
  </select>
</div>
<button id="toggle">Show underlying select</button>


</body>
</html>
  • It doesn’t have the phrase: "Select an option below" or something like that! Select one... from it only works if you click on the button to display Select. And that I would not like to do. So I would like to fill in his text box

  • @Carlosrocha on the official page doesn’t really have, but in the code I posted there is yes, take a look at the first option <option value="">Select one...</option>. I’ll post an image there.

  • Note that in your code there is dbText( type['text']) empty. But select is filled. I need to fill in dbText( type['text']), DO NOT select it. select is already filled in correctly. Understand?

  • I was thinking about changing the value of this field here: Something like: $( "#fieldName" ).value(); But I don’t know how to do it because I don’t have the field name!

  • Now I get it! Is that the autocomplete did not accept value="". I put value="#" and it worked!

0

You need to define a "value" for the option "Select". Behold:http://jsfiddle.net/emirdeliz/swqwLfxu/

<select id="combobox">
    <option value="selecione">Select algo</option>
    <option value="ActionScript">ActionScript</option>
    <option value="AppleScript">AppleScript</option>
    <option value="Asp">Asp</option>
    <option value="BASIC">BASIC</option>
    <option value="C">C</option>
    <option value="C++">C++</option>
    <option value="Clojure">Clojure</option>
    <option value="COBOL">COBOL</option>
    <option value="ColdFusion">ColdFusion</option>
    <option value="Erlang">Erlang</option>
    <option value="Fortran">Fortran</option>
    <option value="Groovy">Groovy</option>
    <option value="Haskell">Haskell</option>
    <option value="Java">Java</option>
    <option value="JavaScript">JavaScript</option>
    <option value="Lisp">Lisp</option>
    <option value="Perl">Perl</option>
    <option value="PHP">PHP</option>
    <option value="Python">Python</option>
    <option value="Ruby">Ruby</option>
    <option value="Scala">Scala</option>
    <option value="Scheme">Scheme</option>
  </select>

If you want to use a blank value just remove the "text" from the option as below:

  <select id="combobox">
    <option value="selecione"></option>
    <option value="ActionScript">ActionScript</option>
    <option value="AppleScript">AppleScript</option>
    <option value="Asp">Asp</option>
    <option value="BASIC">BASIC</option>
    <option value="C">C</option>
    <option value="C++">C++</option>
    <option value="Clojure">Clojure</option>
    <option value="COBOL">COBOL</option>
    <option value="ColdFusion">ColdFusion</option>
    <option value="Erlang">Erlang</option>
    <option value="Fortran">Fortran</option>
    <option value="Groovy">Groovy</option>
    <option value="Haskell">Haskell</option>
    <option value="Java">Java</option>
    <option value="JavaScript">JavaScript</option>
    <option value="Lisp">Lisp</option>
    <option value="Perl">Perl</option>
    <option value="PHP">PHP</option>
    <option value="Python">Python</option>
    <option value="Ruby">Ruby</option>
    <option value="Scala">Scala</option>
    <option value="Scheme">Scheme</option>
  </select>
  • Yes, but in the case of form editing, how to change this option to the option with the bank value? My select is already like this. The problem is popular type["text']. You can make an html and post in your answer fazendol favor?

  • Take the example @Carlosrocha

  • Yeah. But if I copy and paste doesn’t work right. It seems like something’s missing, you know? I’ve had this problem here and the staff gave me all the html and then it worked. I tested it here but only leaves the option selet

  • Copy and paste: <option value="select"></option>

  • Or copy from here: http://jsfiddle.net/emirdeliz/swqwLfxu/

  • Now I get it! Is that the autocomplete did not accept value="". I put value="#" and it worked!

  • You can close the thread ;)

  • I need another help still here. where in this code, is the autocomplete letter by typed letter? Is that I need to do a search every time the autocomplete completes until I find a match with select!

  • This routine is from the Jquery plugin itself. If I understand your doubt, as the user is typing, if none of the options meet your filter, a new query should be made bringing only the records that meet what the user typed. Would that be?

  • Kind of. I typed the letter A, there is no combination in the select option, I typed the letter c, there is no combination in the select option, after a few keystrokes, I arrived in the 'Action Script' formation, there is an option either in the li created dynamically or in one of the option options, then fires the ajax. Shoot the ajax I can, but find a way to do it by the difficult ta keydown.

  • Look want strange thing occurs. I did: this.input.on("keydown", Function () { Alert($("this.input"). val()); }); The keydown occurs within the field. but the Alert() says the field is undefined

  • Vixi, I’m curled up now, tonight I take a look OK?

  • ta good. no problems. Good work and even note!

  • Try giving a console.log the value

Show 9 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.