Jump to content

Setting the "Value" Attribute of An HTML Input Tag To An ID From a JSON Table


phdphd

Recommended Posts

Hi All,

I have a form with a jquery autocomplete input field. Once the user has entered 2 characters, there is a list of values (people names) containing this string that appears. This works good.

The values come from a database table with two fields (names and ids). The query that extracts the names also retreives the values in the id field.

What would be the syntax to set the "value" attribut of the input tag to the id of a name when the user clicks on that name in the list?

 

The PHP part that builds the json is :

$data[] = array(
'label' => $row['name'],
'value' => $row['name'],
'id' => $row['id']
);
echo json_encode($data);

The JS begins as follows :

jQuery(document).ready(function(){
$('#input_id').autocomplete({source:'my_jquery_suggest.php',    select: function(event, ui) {
                $(event.target).val(ui.item.value);
                $('#form_id').submit();
                return false;
            },
minLength:2,delay: 1000}).focus(function () {
               
                window.pageIndex = 0;
                $(this).autocomplete("search");
            });
...

Thanks for your help.

Without knowing anything about the autocomplete api you are using, probably something very similar to what you are doing here:

//Populate autocomplete box with selected VALUE
$(event.target).val(ui.item.value);

//Populate some other input with selected ID
$(some_other_input).val(ui.item.id)

You must be using a plugin, as the main jQuery library does not have an autocomplete function. Is this solved or do you need more help?

 

The only thing I left out is on your form you'd want to create an input, probably a hidden input, to store the ID so it gets sent with the form on submit. That's what $(some_other_input).val(ui.item.id); is eluding to.

Thanks a lot, CroNiX, it is working. Now the beginning of the JS looks like this (the only change is the insertion of "$('#some_other_input_id').val(ui.item.id);":

jQuery(document).ready(function(){
$('#input_id').autocomplete({source:'my_jquery_suggest.php',    select: function(event, ui) {
                $(event.target).val(ui.item.value);
		$('#some_other_input_id').val(ui.item.id);
                $('#form_id').submit();
                return false;
            },
			minLength:2,delay: 1000}).focus(function () {
               
                window.pageIndex = 0;
                $(this).autocomplete("search");
            });

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.