Forum

November 2nd, 2014
A A A
Avatar

Lost password?
Advanced Search

— Forum Scope —




— Match —





— Forum Options —





Minimum search word length is 3 characters - maximum search word length is 84 characters

The forums are currently locked and only available for read only access
sp_Feed Topic RSS sp_TopicIcon
auto complete
26/04/2009
21:26
Avatar
redsuitee
Member
Members
Forum Posts: 35
Member Since:
16/04/2009
sp_UserOfflineSmall Offline

can anybody give me some example to build an auto complete program..

thanx

-md-

"God Gave you a gift of 86,400 seconds today.
Have you used one to say thank you?"

21/08/2009
03:57
Avatar
dhubenov
Stara Zagora, Bulgaria
Member
Members
Forum Posts: 8
Member Since:
21/08/2009
sp_UserOfflineSmall Offline

Hi redsuitee,

It's quite easy job. You probably already have found the solution for this problem but it may be usefull to someone else too.
First of all you'll need an autocomplete jQuery plugin. I would recomend  Autocomplete – jQuery plugin (current version 1.0.2)   by Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer. You can find it here
 
This is a simplified example of setting autocomplete to a two fields:

  • one of them holding the ID (value) of what we need (hidden one)
  • the other (visible in the edit dialog) – holding the value (label, text, you name it)

You can think of this model as a select but we need couple of columns to hold both value and visible text

  1. Make sure you included the autocomplete plugin files in the header:
    <link href="your_path_to/autocomplete/jquery.autocomplete.css" type="text/css" rel="stylesheet" />
    <script src="your_path_to/autocomplete/jquery.autocomplete.js" type="text/javascript"></script>
  2. Integrate autocompleter as follows
    $(”#querieslist”)..jqGrid({
      // … some grid options …
      colModel :[
         { // ... some column definitions ... },
         {
            name:'my_customId', index:'my_customId',
            editable:true, hidden:true, search:false
          }, {
            name:'my_customName', index:'my_customName', label: 'My automplete column', width:200,
              editable:true,
              edittype:'text', // edittype's default is 'text' so you don't really need it here.
              editoptions: {
                size:64,
                maxlength:255,
                dataInit:function (elem) { // the moment of magic Wink
                $(elem)
                  .autocomplete( // for more info check the autocomplete plugin docs
                    'path_to_serverside.php?some_get_option=if_we_need_it&another_option=goes_here', {
                      dataType: 'ajax',
                      multiple: false,
                      parse: function(data) { // parsing json input
                          return $.map(eval(data), function(row) {
                          return (typeof(row) == 'object')
                            ? { data: row, value: row.res_id, result: row.res_name } // same in the serverside
                            : { data: row, value: '',      result: ''        };
                        });
                      },
                      formatItem: function(item) {
                        return (typeof(item) == 'object')?item.res_name :'';
                      }
                    }
                  )
                  .result(function(e, item) {
                    $("#my_customId").val(item.res_name );
                  });
              }}, 
              searchoptions:{sopt:['bw','bn','eq','ne','ew','en','cn','nc','in','ni']}
            },
            { // … some column definitions … }

    });

  3. Now let's have a look at the serverside script (.php)

    header('Content-Type: application/x-json; charset=utf-8');
    // both vars are generated by autocomplete so you just catch them here
    $q = $_GET['q'];
    $limit = $_GET['limit']
    // don't forget to catch your own variables (if you set some)
    // …

    // I will not bother to explain sql query in details – I'm sure you can figure it out
    // It will look like:
    $mySqlQuery = mysql_query(”SELECT `id`, `value` FROM `sqlTable` WHERE `value` LIKE '%”.mysql_real_escape_string($q).”%' LIMIT “.mysql_real_escape_string($limit));
    $res = array();
    if (mysql_num_rows($mySqlQuery) > 0) {
        while ($row = mysql_fetch_assoc($mySqlQuery)) {
           $res[] = '{
    res_id:”'.str_replace('”','\\\\”',$t_row['id']).'”,res_name:”'.str_replace('”','\\\\”',$t_row['value']).'”}';
        }

     } else {
         $res[] = '{res_id:”0″,res_name:”Try again”}';
            }
      echo '['.implode(',',$res).']'; exit;

I hope this post will give you a clue HOW to make it. If you have more specific questions – just ask.

09/09/2010
09:45
Avatar
bhoomi
New Member
Members
Forum Posts: 1
Member Since:
09/09/2010
sp_UserOfflineSmall Offline

Hi,

I am having the same problem. Looked at almost all the samples but none work for me.

M using ASP.NET MVC. Grid populates the data. Form editing is working fine. On submit it posts the data to corresponding controller.

But in Autocomplete controller method is not invoked. Tried everything pl help.

Below is my code :

$("#RegionAndCity").jqGrid({
            url: '/BriefAllocation/GetRegionAndCities/?briefId=' + briefallocationid,
            datatype: 'json',
            mtype: 'GET',
            prmNames: {
                briefId: briefallocationid
            },
            colNames: ['AllocatedRegionAndCitiesId', 'BriefAllocationId', 'LocationId', 'LocationName', 'PlannerId', 'Region', 'Budget'],
            colModel: [
                                  { name: 'AllocatedRegionAndCitiesId', index: 'AllocatedRegionAndCitiesId', width: 100, align: 'left', /* key: true,*/editable: true, editrules: { edithidden: false }, hidedlg: true, hidden: true },
                                  { name: 'BriefAllocationId', index: 'BriefAllocationId', width: 150, align: 'left', editable: false, edittype: 'text', editrules: { required: true }, formoptions: { elmsuffix: ' *'} },
                                  { name: 'LocationId', index: 'LocationId', width: 150, align: 'left', editable: false, edittype: 'text', editrules: { required: true }, formoptions: { elmsuffix: ' *'} },
                                  { name: 'LocationName', index: 'LocationName', width: 300, align: 'left', editable: true, edittype: 'text',
                                      editoptions: { dataInit: function (elem) {
                                          setTimeout(function () {
                                              $(elem).autocomplete('<%= Url.Action("FindLocation" , "Shared" ) %>', {
                                                  dataType: "ajax",
                                                  multiple: false,
                                                  formatItem: function (item, index, total, query) {
                                                      return item.value;
                                                  },                                                 
                                                  parse: function (data) {
                                                      return $.map(data, function (item) {
                                                          return {
                                                              data: item,
                                                              value: item.Key,
                                                              result: item.value
                                                          }
                                                      });
                                                  }
                                              }).result(function (event, row) {
                                                  $("#LocationId").val(row.Key);
                                              });                                                
                                          }, 100);
                                      }
                                      }, editrules: { required: true }
                                  }
                                 ,
                                  { name: 'PlannerId', index: 'PlannerId', width: 150, align: 'left', editable: true, edittype: 'text', editrules: { required: false} },
                                  { name: 'Region', index: 'Region', width: 100, align: 'left', editable: true, edittype: 'text', editrules: { required: true }, formoptions: { elmsuffix: ' *'} },
                                  { name: 'Budget', index: 'Budget', width: 100, align: 'left', editable: true, edittype: 'text', editrules: { required: true }, formoptions: { elmsuffix: ' *'} },
                                ],
           beforeEditCell:function(rowid,cellname,value,irow,icol){
                                alert("Before Edit!");
                        },
            pager: $('#listPager'),
            rowNum: 10,
            rowList: [5, 10, 20, 50],
            sortname: 'AllocatedRegionAndCitiesId',
            sortorder: "asc",
            viewrecords: true,
            imgpath: '/scripts/themes/steel/images',
            caption: '<b>Regions And Cities</b>',
            ondblClickRow: function (rowid, iRow, iCol, e) {
                $("#RegionAndCity").editGridRow(rowid, prmGridDialog);
            }
        }).navGrid('#listPager', { edit: true, add: true, del: true, refresh: true },
                updateDialog,
                updateDialog,
                updateDialog);

M trying to populate locationName.

On server side i have

        public ActionResult FindLocation(string q, int limit)
        {
            string q="";
           ///Get json data. This method works for autocomplete outside grid.
            return Content(json);
        }

Pl help.

12/09/2010
09:47
Avatar
dhubenov
Stara Zagora, Bulgaria
Member
Members
Forum Posts: 8
Member Since:
21/08/2009
sp_UserOfflineSmall Offline

Hi, bhoomi

Have a look at this line:

return $.map(data, function (item) {...});

At this point data is just a STRING containing JSON object... so for us to be able to use the object - we need to convert the string using eval() function.

So I think the solution for your trouble is to modify the line like:

return $.map(eval(data), function (item) {...});

Please post a reply if this fixes the issue.

29/10/2010
14:17
Avatar
antonia
New Member
Members
Forum Posts: 2
Member Since:
29/10/2010
sp_UserOfflineSmall Offline

Hi dhubenov,

many thanks for your work.

It works nicely but on one part I have a problem. The my_customId is not posted to the server.

It is this code:

.result(function(e, item) {
           $("#my_customId").val(item.res_name );
 });

 

First of all I think this should be "item.res_id". But still the variable is not set correctly.

Then it seems to me as if it would be a id-element. But since we are in the context of the colModel I am not sure how to address it correctly.

Do you have any hint so that the ID gets posted correctly? my_customName works as it should.

Thanks again

Antonia

30/10/2010
06:29
Avatar
dhubenov
Stara Zagora, Bulgaria
Member
Members
Forum Posts: 8
Member Since:
21/08/2009
sp_UserOfflineSmall Offline

Antonia,

You are right. It is my mistake in post #2.
The correct line is:

.result(function(e, item) {
           $("#my_customId").val(item.res_id );
 });

Sorry about that.

Btw the Autocomplete plugin is already part of jQuery UI. You can find some more information at jqueryui.com/demos/autocomplete

If you need further help you can send some source to my email <use_my_nickname@gmail.com>

31/10/2010
09:30
Avatar
antonia
New Member
Members
Forum Posts: 2
Member Since:
29/10/2010
sp_UserOfflineSmall Offline

Hi dhubenov,

thanks for answering so fast (even after such a long time after your initial post 🙂 ).

Regarding the item.res_id: that was actually no problem, as it is logic to me after implementation.

The main problem which I face is that I don't get any value posted from the form for the variable "my_customId".

I actually don't understand how to update the my_customId from within the colModel when choosing the my_customName.

It seems you have another div or span within your html code with the ID "my_customID" but how would you use it in the form?

My scenario currently: Usual grid and the colModel with the entries my_customName and my_customId.

Autocomplete works fine.

But when submitting only the post variable my_customName is set with the correct name / value of the element (that's perfect) but the variable my_customId is empty.

I do understand that it is the last "return" statement posted in my initial post which should set the my_customId but maybe I missed something else ?

Many thanks

Antonia

02/11/2010
02:41
Avatar
dhubenov
Stara Zagora, Bulgaria
Member
Members
Forum Posts: 8
Member Since:
21/08/2009
sp_UserOfflineSmall Offline

Hi Antonia,

If you have another look at post #2 you'll see the following code:
     {
        name:'my_customId', index:'my_customId',
        editable:true, hidden:true, search:false
      }
This is a hidden column of the grid. But besause it is editable, when the add/edit dialog is generated, there will be an input element with id and name my_customId . So it isn't a div or span - a simple input Wink
How do we update its value on selection? With this line:
$("#my_customId").val(item.res_id);

I can't tell what is wrong with your code. My cristal ball is broken ... couple of months already Laugh
But I have another idea. I've made an example and you are free to download it from here. I've tried to keep it simple - no DB or any fancy stuff in it. I hope you'll find it useful and it will give you a better understanding of where is the troublemaker.

Happy coding! And don't hesitate to ask for more help. Smile

02/11/2010
09:34
Avatar
dhubenov
Stara Zagora, Bulgaria
Member
Members
Forum Posts: 8
Member Since:
21/08/2009
sp_UserOfflineSmall Offline

Just an update to the last post:

The examples file now includes both form- and inline-editing examples.

In order to use autocomplete plugin with inline editing you just need to modify this part:
.result(function(e, item) {
           $("#"+ variable_holding_row_id +"_my_customId").val(item.res_id );
 });
Apparently jqgrid is building the name and id of the input tag in different manner. The difference is that in inline editing you have to add the rowId of the currently edited row. That's all.

Have a great day.

Forum Timezone: Europe/Sofia

Most Users Ever Online: 715

Currently Online:
36 Guest(s)

Currently Browsing this Page:
1 Guest(s)

Top Posters:

OlegK: 1255

markw65: 179

kobruleht: 144

phicarre: 132

YamilBracho: 124

Renso: 118

Member Stats:

Guest Posters: 447

Members: 11373

Moderators: 2

Admins: 1

Forum Stats:

Groups: 1

Forums: 8

Topics: 10592

Posts: 31289

Newest Members:

, razia, Prankie, psky, praveen neelam, greg.valainis@pa-tech.com

Moderators: tony: 7721, Rumen[Trirand]: 81

Administrators: admin: 66

Comments are closed.
Privacy Policy   Terms and Conditions   Contact Information