AutoComplete jQuery Using JSON data
Asked Answered
F

4

6

Imagine a json file with the following data:

[
    {
        color: "red",
        value: "#f00"
    },
    {
        color: "green",
        value: "#0f0"
    },
    {
        color: "blue",
        value: "#00f"
    },
    {
        color: "cyan",
        value: "#0ff"
    }
]

Using jQuery's autocomplete method, I want it to be able to display the color as options to select and insert value on a input.

<input type="text" name="selector" id="selector" />

<input type="text" name="color" id="color" />
<input type="text" name="value" id="value" />

The above doesn't need introductions. Selector for the search on the colors, input.color with color value and input.value with value value.

EDIT: I have this JSON data:

[{
    "label": "Sec\u00e7\u00e3o 1",
    "value": "1"
}, {
    "label": "Sec\u00e7\u00e3o 2",
    "value": "2"
}, {
    "label": "Sec\u00e7\u00e3o 3",
    "value": "3"
}, {
    "label": "Sec\u00e7\u00e3o 4",
    "value": "4"
}]

and this HTML:

<input type="text" id="name" />
<input type="text" id="value" />

and this jQuery:

$(document).ready(function(){
    $("#name").autocomplete({
        source: "json.php",
        select: function (event, ui) {
            $("#name").val(ui.label);
            $("#value").val(ui.value);
        }
    });
});

I followed Andrew's answer and it prompts me to select the data, but if I alert ui.labeland ui.value variables, it says 'undefined'. What am I missing?

Edit2: Let's say I have this HTML:

<input type="text" class="name" />
<input type="text" class="value" />

<input type="text" class="name" />
<input type="text" class="value" />

Is it possible to handle multiple selectors with the same .autocomplete() method? Like, select the label I want using the input.name and only update the input.value next to it?

[input.name] [input.value]
^ I select       ^ updates the
  a label           value next to it
[input.name] [input.value]
^ this stays intact ^

Fusil answered 17/7, 2012 at 23:18 Comment(3)
Are you using a remote or local data source?Prostate
It will be a php file getting the values from a DB and encoding them in JSON format...Fusil
I haven't tried much, as I was still trying to figure out what was the right way to use jQuery's autocomplete...Fusil
P
14

Using a remote data source:

$("#selector").autocomplete({
    source: function (request, response) {
         $.ajax({
             url: "my_server_side_resource.php",
             type: "GET",
             data: request,
             success: function (data) {
                 response($.map(data, function (el) {
                     return {
                         label: el.color,
                         value: el.value
                     };
                 }));
             }
         });
    },
    select: function (event, ui) {
        // Prevent value from being put in the input:
        this.value = ui.item.label;
        // Set the next input's value to the "value" of the item.
        $(this).next("input").val(ui.item.value);
        event.preventDefault();
    }
});

Tweak the $.ajax call as needed. This example will generate requests to your PHP resource that look like this:

my_server_side_resource.php?term=xyz

If you have control over your server-side code, you could change the data that's returned to look like this:

[
    {
        label: "red",
        value: "#f00"
    }, /* etc */
]

You can simply use a string, the name of your server-side resource as the source:

$("#selector").autocomplete({
     source: "my_server_side_resource.php",
     select: /* same as above */
});

Check out the remote with JSONP example for a full example using a server-side resource.

Edit: See this example for a working demo using local data: http://jsfiddle.net/SMxY6/

Prostate answered 17/7, 2012 at 23:26 Comment(6)
That looks like it will do the trick, just gotta test it! Thanks for the fast answer ;)Fusil
@silentw: Sorry I had a small bug in my code! You want ui.item.label not just ui.label.Prostate
Thanks, it worked out! Now I have a small problem... I'm using the input#name for both selector and label... But after selection, it changes the value to value instead of label...Fusil
@silentw: See my update to the select event. You might also want to do the same thing in the focus event.Prostate
This is awesome, it works out as I wanted! Check my edit2 to see if that is possible...Fusil
Thanks a lot, it does the trick! Accepted your answer, thanks for your help! :)Fusil
H
2

You need to change your JSON object to use the "label" property. From the docs:

An Array of Objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]

The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.

Then, you need to set the values of the other text fields when the "change" or "select" events are fired.

Helse answered 17/7, 2012 at 23:30 Comment(0)
T
1
$(function() {
            $("#subject_name").autocomplete({
                    source: function(request, response) {
                        $.ajax({
                            url: "api/listBasicsubject",
                            dataType: "json",
                            type: "POST",
                            data: {
                                subject_name: request.term,

                            },
                            success: function(data) {
                                response($.map(data.data, function(item) {
                                        return {
                                            label: item.subject_name,
                                            value: item.subject_name

                                        }
                                    });
                                }


                            },
                            autoFocus: true,
                            minLength: 1
                        });
                    });
            });
Technics answered 6/9, 2019 at 10:7 Comment(0)
N
0

After hours of working.. Finally made it happen. Thing is I have a json array consisting of many json objects. Each json object has bank name and its ifsc code.User needed to Type bank and filter out bank detail row from database. Upon selecting that bank... I had 2 input fields one for bank and other for ifsc code. I select bank name and corresponding ifsc code is shown. So this is how i did it:-


<script type="text/javascript">
$(function() {





    $("#newBeneBankName").autocomplete({

        source: function(request, response) {

            $.ajax({
                url: "getBankDetailsIFSCJson",
                type: "GET",
                data: {
                    term: request.term
                },
                dataType: "json",
                success: function (data) {
                    response($.map(data, function (el) {
                        return {
                            label: el.label,
                            value: el.value
                        };
                    }));
                }
            });
        }, //newBeneBankName addBeneIfscCode
        focus: function (event, ui) {
            event.preventDefault();
            $("#newBeneBankName").val(ui.item.label);
        },
        select: function (event, ui) {
            event.preventDefault();
            $("#addBeneIfscCode").val(ui.item.value);
            $("#newBeneBankName").val(ui.item.label);
        }

});
});


my json array= [ { label:"state bank of india", value:"SBIN00076" }, { label:"ICICI Bank", value:"ICIC001" },.. ]

Niccolo answered 28/2, 2018 at 8:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.