jQuery UI autocomplete with item and id

前端 未结 11 1764
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 00:32

I have the following script which works with a 1 dimensional array. Is it possible to get this to work with a 2 dimensional array? Then whichever item is selected, by clic

相关标签:
11条回答
  • 2020-11-29 00:39

    Assuming the objects in your source array have an id property...

    var $local_source = [
        { id: 1, value: "c++" },
        { id: 2, value: "java" },
        { id: 3, value: "php" },
        { id: 4, value: "coldfusion" },
        { id: 5, value: "javascript" },
        { id: 6, value: "asp" },
        { id: 7, value: "ruby" }];
    

    Getting hold of the current instance and inspecting its selectedItem property will allow you to retrieve the properties of the currently selceted item. In this case alerting the id of the selected item.

    $('#button').click(function() {
        alert($("#txtAllowSearch").autocomplete("instance").selectedItem.id;
    });
    
    0 讨论(0)
  • 2020-11-29 00:40

    Just want to share what worked on my end, in case it would be able to help someone else too. Alternatively based on Paty Lustosa's answer above, please allow me to add another approach derived from this site where he used an ajax approach for the source method

    http://salman-w.blogspot.ca/2013/12/jquery-ui-autocomplete-examples.html#example-3

    The kicker is the resulting "string" or json format from your php script (listing.php below) that derives the result set to be shown in the autocomplete field should follow something like this:

        {"list":[
         {"value": 1, "label": "abc"},
         {"value": 2, "label": "def"},
         {"value": 3, "label": "ghi"}
        ]}
    

    Then on the source portion of the autocomplete method:

        source: function(request, response) {
            $.getJSON("listing.php", {
                term: request.term
            }, function(data) {                     
                var array = data.error ? [] : $.map(data.list, function(m) {
                    return {
                        label: m.label,
                        value: m.value
                    };
                });
                response(array);
            });
        },
        select: function (event, ui) {
            $("#autocomplete_field").val(ui.item.label); // display the selected text
            $("#field_id").val(ui.item.value); // save selected id to hidden input
            return false;
        }
    

    Hope this helps... all the best!

    0 讨论(0)
  • 2020-11-29 00:43

    Auto Complete Text box binding using Jquery

      ## HTML Code For Text Box and For Handling UserID use Hidden value ##
      <div class="ui-widget">
    @Html.TextBox("userName")  
        @Html.Hidden("userId")
        </div>
    

    Below Library's is Required

    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/resources/demos/style.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    

    Jquery Script

    $("#userName").autocomplete(
    {
    
        source: function (request,responce)
        {
            debugger
            var Name = $("#userName").val();
    
            $.ajax({
                url: "/Dashboard/UserNames",
                method: "POST",
                contentType: "application/json",
                data: JSON.stringify({
                    Name: Name
    
                }),
                dataType: 'json',
                success: function (data) {
                    debugger
                    responce(data);
                },
                error: function (err) {
                    alert(err);
                }
            });
        },
        select: function (event, ui) {
    
            $("#userName").val(ui.item.label); // display the selected text
            $("#userId").val(ui.item.value); // save selected id to hidden input
            return false;
        }
    })
    

    Return data Should be below format


     label = u.person_full_name,
     value = u.user_id
    
    0 讨论(0)
  • 2020-11-29 00:47

    I've tried above code displaying (value or ID) in text-box insted of Label text. After that I've tried event.preventDefault() it's working perfectly...

    var e = [{"label":"PHP","value":"1"},{"label":"Java","value":"2"}]
    
    $(".jquery-autocomplete").autocomplete({
        source: e,select: function( event, ui ) {
            event.preventDefault();
            $('.jquery-autocomplete').val(ui.item.label);
            console.log(ui.item.label);
            console.log(ui.item.value);
        }
    });
    
    0 讨论(0)
  • 2020-11-29 00:49

    I do not think that there is need to hack around the value and label properties, use hidden input fields or to suppress events. You may add your own custom property to each Autocomplete object and then read that property value later.

    Here is an example.

    $(#yourInputTextBox).autocomplete({
        source: function(request, response) {
            // Do something with request.term (what was keyed in by the user).
            // It could be an AJAX call or some search from local data.
            // To keep this part short, I will do some search from local data.
            // Let's assume we get some results immediately, where
            // results is an array containing objects with some id and name.
            var results = yourSearchClass.search(request.term);
    
            // Populate the array that will be passed to the response callback.
            var autocompleteObjects = [];
            for (var i = 0; i < results.length; i++) {
                var object = {
                    // Used by jQuery Autocomplete to show
                    // autocomplete suggestions as well as
                    // the text in yourInputTextBox upon selection.
                    // Assign them to a value that you want the user to see.
                    value: results[i].name;
                    label: results[i].name;
    
                    // Put our own custom id here.
                    // If you want to, you can even put the result object.
                    id: results[i].id;
                };
    
                autocompleteObjects.push(object);
            }
    
            // Invoke the response callback.
            response(autocompleteObjects);
        },
        select: function(event, ui) {
            // Retrieve your id here and do something with it.
            console.log(ui.item.id);
        }
    });
    

    The documentation mentions you have to pass in an array of objects with label and value properties. However, you may certainly pass in objects with more than these two properties and read them later.

    Here is the relevant part I am referring to.

    Array: An array can be used for local data. There are two supported formats: An array of strings: [ "Choice1", "Choice2" ] 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 when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only value properties, the value will also be used as the label.

    0 讨论(0)
  • 2020-11-29 00:50

    You need to use the ui.item.label (the text) and ui.item.value (the id) properties

    $('#selector').autocomplete({
        source: url,
        select: function (event, ui) {
            $("#txtAllowSearch").val(ui.item.label); // display the selected text
            $("#txtAllowSearchID").val(ui.item.value); // save selected id to hidden input
        }
    });
    
    $('#button').click(function() {
        alert($("#txtAllowSearchID").val()); // get the id from the hidden input
    }); 
    

    [Edit] You also asked how to create the multi-dimensional array...

    You should be able create the array like so:

    var $local_source = [[0,"c++"], [1,"java"], [2,"php"], [3,"coldfusion"], 
                         [4,"javascript"], [5,"asp"], [6,"ruby"]];
    

    Read more about how to work with multi-dimensional arrays here: http://www.javascriptkit.com/javatutors/literal-notation2.shtml

    0 讨论(0)
提交回复
热议问题