Nick
Nick

Reputation: 1869

Jquery AutoComplete : How to get the selected items id?

I have an auto complete field which is working perfectly, and fetch the data from the database. When user selects a result from the response, i want to save the id of the selected item in a hidden field.

Here is the code I'm using for autocomplete

 $jQNetbmis("input#txt_client_name").autocomplete("autosuggest_clientmaster.php", {
        width: 160,
        mustMatch: true,
        selectFirst:false,
        formatResult: function(row) {
            var resStr = row.toString();
            temp = resStr.substring(0,resStr.indexOf("+"));
            return temp;
        },
        formatItem: function(row, i, max) {
            var resStr = row.toString();
            var temp = resStr.substring(0,resStr.indexOf("+"));
            return temp;
        }
     }); 

Following is the response that i get i press n

name 1+50
Name 2+85
Name 3+86
Name 4+98
Name 5 +103

If the user selects name 1 i want to save 50 in to the hidden field .

I'm using Autocomplete - jQuery plugin 1.0.2

Krishnik

Upvotes: 1

Views: 5856

Answers (3)

Mathias E.
Mathias E.

Reputation: 471

I don't really know the autocomplete you're using but the problem doesn't seem to come from it.

Just concatenate the id with the existing value of the hidden field :

$jQNetbmis("input#txt_client_name").autocomplete("autosuggest_clientmaster.php", {
    width: 160,
    mustMatch: true,
    selectFirst:false,
    formatResult: function(row) {
        var resStr = row.toString();
        //temp = resStr.substring(0,resStr.indexOf("+"));
        var temp = resStr.split('+');
        $('input#hidden_field').val($('input#hidden_field').val()+'+'+temp[1]);
        return temp[0];
    },
    formatItem: function(row, i, max) {
        var resStr = row.toString();
        var temp = resStr.substring(0,resStr.indexOf("+"));
        return temp;
    }
 }); 

Upvotes: 0

Jura Khrapunov
Jura Khrapunov

Reputation: 1024

jQuery UI has an excellent autocomplete widget which is pretty well documented: http://jqueryui.com/demos/autocomplete/. Your case is also there so go through examples.

Upvotes: 0

Yi Jiang
Yi Jiang

Reputation: 50095

You can use the result handler to do this. An example of how you might wish to accomplish this is:

$('input#txt_client_name').result(function(event, data){
    $('input#hidden_field').val(data.substring(data.indexOf('+') + 1));
});

The handler is ran every time the user selects an item. As an aside, you might want to use the jQuery UI Autocomplete instead of this plugin, which is deprecated in favor of that.

Upvotes: 1

Related Questions