Skip to content Skip to sidebar Skip to footer

Jquery Multiple Autocomplete Field

I have the jquery auto complete from the jquery website. it is working just fine for one field. However now I want to add different field with different values in it, how do I do t

Solution 1:

So I did an example to explain to you what you need to do to make more inputs.

FIDDLE: http://jsfiddle.net/6wTHK/6/not as in the code below

Lets say we have two inputs :

<input  name="project1"id="searchbox1" placeholder="Cmpt 1"/>
<input  name="project2"id="searchbox2" placeholder="Cmpt 2"/>

#searchbox1 has it's values saved in the var projects1

var projects1 = [
      {
        value: "CMPT101",
        label: "CMPT 101",
        desc: "Discrete Mathematics I"
},
{
        value: "CMPT102",
        label: "CMPT 102",
        desc: "Discrete Mathematics II"
},
{
        value: "CMPT103",
        label: "CMPT 103",
        desc: "Discrete Mathematics III"
}];

#searchbox2 has it's values saved in the var projects2

var projects2 = [
          {
            value: "CMPT104",
            label: "CMPT 105",
            desc: "Discrete Mathematics IV"
    },
    {
            value: "CMPT106",
            label: "CMPT 106",
            desc: "Discrete Mathematics V"
    },
    {
            value: "CMPT107",
            label: "CMPT 107",
            desc: "Discrete Mathematics VI"
    }];

Now for each input we add the .autocomplete() function;

 $( "#searchbox1" ).autocomplete({ //change #searchbox2 to your input idminLength: 0,
      source: projects1, //change here the source of your valuesfocus: function( event, ui ) {
        $( "#searchbox1" ).val( ui.item.label );
        //you had more stuff herereturnfalse;
      },
      select: function( event, ui ) {
        $( "#searchbox1" ).val( ui.item.label );
        //you had more stuff herereturnfalse;
      }, 
      })
    .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
      return $( "<li>" )
        .append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
        .appendTo( ul );
    };

And for the second input

$( "#searchbox2" ).autocomplete({ //change #searchbox2 to your input idminLength: 0,
          source: project2, //change here the source of your valuesfocus: function( event, ui ) {
            $( "#searchbox2" ).val( ui.item.label );
            //you had more stuff herereturnfalse;
          },
          select: function( event, ui ) {
            $( "#searchbox2" ).val( ui.item.label );
            //you had more stuff herereturnfalse;
          }, 
          })
        .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
          return $( "<li>" )
            .append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
            .appendTo( ul );
        };

Post a Comment for "Jquery Multiple Autocomplete Field"