views:

187

answers:

1

using jquery autocomplete, we get hidden value by calling .result function like this

$("#suggest").result(function(event, data, formatted) {
   $('#hidden').val(data[1]);
 });

This is only useful when we selected the option from autosuggest list and press enter. What i need is that i enter the option by typing the complete word without selecting it and clicking on Ok button? but i am always getting empty.

<input type="text" id="suggest" />
<input type="button" value="Ok" onclick="GetValue()" />
<input type="hidden" id="hidden"/>
function GetValue()
{
   //get hidden field value - getting empty
  var hid=document.getElementById('hidden').value;
}
A: 

Edit: Based on your comments you need to do something like this:

var users = [ {value: "John", id: 1}, {value: "George", id: 2},
               {value: "Jim", id: 3} ];

var usersArray = $.map(users, function(el) { return el.value; } );


$(function(){  

  $("#suggest").autocomplete(usersArray);  

  // This handles an autocomplete selection
  $("#suggest").result(function(event, data, formatted) {
     UpdateValue();
   });

  // This handles the manual entry case 
  $("#suggest").keyup(function() {
    UpdateValue();
  });   

});

function UpdateValue()
{
    var name=$("#suggest").val();
    $("#DebugField").text(name);
    $.each(users, function(n, item) {
      if (item.value == name) {
          $('#hidden').val(item.id);
          $("#DebugField").text(item.id);
      }
    });
}


function GetValue()
{
   //get hidden field value - getting empty
  var hid=$('#hidden').val();
  alert(hid);
  return false;
}

See it running here.

kgiannakakis
thanks but this will give textbox value, bcos in autosuggest list i m displaying username and in backend i m getting its userid to be stored in hidden field.i need userid onclick of button
gabriel
The above code will update the value of the hidden field, whenever the value of the autocomplete box changes, whether if it is through typing or an autocomplete selection. The GetValue function needs not to change. See it running in http://jsbin.com/oxopa3
kgiannakakis
yes it will update hidden field value. but what i mean to say is that i m displaying autosuggest list of "users", and in backend each user have their userid, so in hidden field i need "userid" and not "username"
gabriel
not working type john, dont select it just type the complete word, then click on ok.
gabriel
i m using jquery.autocomplete.js and not jquery UI
gabriel
guys please help me out i m stuck!!
gabriel
See my edited answer
kgiannakakis