Firing the select event on click for jQuery autocomplete

℡╲_俬逩灬. 提交于 2019-12-10 20:09:45

问题


After playing around with jQuery's autocomplete feature a bit, I couldn't get the select event to fire onclick. Which is strange because the onfocus event fires when the mouse is dragged over each element in the list. From what I've tried so far, it doesn't look like there's a built in way to have the select event fired onclick. Am I missing something? Or is there another way that people have dealt with this in the past?

Thanks in advance, Brandon


回答1:


The selected event should fire automatically on click. Consider the following code block. Here I pass in a set of handlers to decide things like what url to use, what label to attach the auto complete behavior to etc. Ultimately making an ajax request to populate the auto complete list.

    ActivateInputFieldSearch: function (callBack, fieldID, urlHandler, labelHandler, valueHandler) {
        $("#" + fieldID).autocomplete({
            source: function (request, response) {
                var requestUrl;
                if (_.isFunction(urlHandler)) {
                    requestUrl = urlHandler(request);
                } else {
                    requestUrl = urlHandler;
                }
                $.ajax({
                    url: requestUrl,
                    dataType: "json",
                    data: {
                        maxRows: 10,
                        searchParameter: request.term
                    },
                    success: function (data) {
                        response($.map(data, function (item) {
                            var dataJson = $.parseJSON(item);
                            return {
                                label: labelHandler(dataJson),
                                value: valueHandler(dataJson),
                                data: dataJson
                            };
                        }));
                    }
                });
            },
            minLength: 0,
            select: function (event, ui) {
                if (callBack) {
                    callBack(ui.item);
                }
            },
            open: function () {
                $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
            },
            close: function () {
                $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
            },
            focus: function (event, ui) {
                $("#" + fieldID).val(ui.item.value);
            }
        });
    }



回答2:


I had a similar problem. I was attempting to use an autocomplete on 3 text boxes. If the user started typing in any of the three text boxes, an ajax call would fire and would return all the distinct combinations of those boxes in the database based on what was typed in them.

The important part of what I'm trying to say is that I had the "mouse click no autocompleting" problem. I had a function firing on select to set the values for all of the text boxes. It was something like this:

function showAutocompleteDropDown( a_options ){

    console.log('options: ' + a_options);

    if ( a_options == "" ){
        // nothing to do
        return;
    }// if

    // find out which text box the user is typing in and put the drop down of choices underneath it
    try{
        // run jquery autocomplete with results from ajax call
        $(document.activeElement).autocomplete({
            source: eval(a_options),
            select: function(event, ui){

                console.log( 'event: ' + event.type );
                console.log( ' running select ' );

                // set the value of the currently focused text box to the correct value
                if (event.type == "autocompleteselect"){
                    console.log( "logged correctly: " + ui.item.value );
                    ui.item.value = fillRequestedByInformation( );
                }
                else{
                    console.log( "INCORRECT" );
                }

            }// select
        });
    }
    catch(e){
        alert( e );
    }// try / catch
}// showAutocompleteDropDown()

function fillRequestedByInformation( ){
    // split the values apart in the name attribute of the selected option and put the values in the appropriate areas
    var requestedByValues = $(document.activeElement).val().split(" || ");

    var retVal = $(document.activeElement).val();

    $(document.activeElement).val("");
    var currentlyFocusedID = $(document.activeElement).attr("id");


    console.log( 'requestedByValues: ' + requestedByValues );
    console.log( 'requestedByValues.length: ' + requestedByValues.length );

    for (index = 0; index < requestedByValues.length; index++ ){
        console.log( "requestedByValues[" + index + "]: " + requestedByValues[index] );
        switch ( index ){
            case 0:
                if ( currentlyFocusedID == "RequestedBy" ){
                    retVal = requestedByValues[index];
                }
                $('#RequestedBy').val(requestedByValues[index]);
                break;
            case 1:
                if ( currentlyFocusedID == "RequestedByEmail" ){
                    retVal = requestedByValues[index];
                }
                $('#RequestedByEmail').val(requestedByValues[index]);
                break;
            case 2:
                if ( currentlyFocusedID == "RequestedByPhone" ){
                    retVal = requestedByValues[index];
                }
                $('#RequestedByPhone').val(requestedByValues[index]);
                break;
            default:
                break;
        }
    }
}// fillRequestedByInformation()

and then I changed it to the following:

function showAutocompleteDropDown( a_options ){

    console.log('options: ' + a_options);

    if ( a_options == "" ){
        // nothing to do
        return;
    }// if

    // find out which text box the user is typing in and put the drop down of choices underneath it
    try{
        // run jQuery autocomplete with results from ajax call
        $(document.activeElement).autocomplete({
            source: eval(a_options),
            select: function(event, ui){

                console.log( 'event: ' + event.type );
                console.log( ' running select ' );

                // set the value of the currently focused text box to the correct value
                if (event.type == "autocompleteselect"){
                    console.log( "logged correctly: " + ui.item.value );
                    ui.item.value = fillRequestedByInformation( ui.item.value );
                }
                else{
                    console.log( "INCORRECT" );
                }

            }// select
        });
    }
    catch(e){
        alert( e );
    }// try / catch
}// showAutocompleteDropDown()

function fillRequestedByInformation( a_requestedByValues ){
    // split the values apart in the name attribute of the selected option and put the values in the appropriate areas
    var requestedByValues = a_requestedByValues.split(" || ");

    var retVal = $(document.activeElement).val();

    $(document.activeElement).val("");
    var currentlyFocusedID = $(document.activeElement).attr("id");


    console.log( 'requestedByValues: ' + requestedByValues );
    console.log( 'requestedByValues.length: ' + requestedByValues.length );

    for (index = 0; index < requestedByValues.length; index++ ){
        console.log( "requestedByValues[" + index + "]: " + requestedByValues[index] );
        switch ( index ){
            case 0:
                if ( currentlyFocusedID == "RequestedBy" ){
                    retVal = requestedByValues[index];
                }
                $('#RequestedBy').val(requestedByValues[index]);
                break;
            case 1:
                if ( currentlyFocusedID == "RequestedByEmail" ){
                    retVal = requestedByValues[index];
                }
                $('#RequestedByEmail').val(requestedByValues[index]);
                break;
            case 2:
                if ( currentlyFocusedID == "RequestedByPhone" ){
                    retVal = requestedByValues[index];
                }
                $('#RequestedByPhone').val(requestedByValues[index]);
                break;
            default:
                break;
        }
    }
}// fillRequestedByInformation()

The debugging is still in there for now, but the change was in the select event in the autocomplete by adding a parameter to the function fillRequestedByInformation() and the first line of said function. It returns to and overwrites ui.item.value to get the correct value for that box instead of the selected value.

Example of a selected autocomplete value:

"John Doe || john.doe@internet.net || 1-222-123-1234"

Also, used eval( a_options ) so that the autocomplete could utilize a_options. before I used eval, it would not even recognize I had values in the source. a_options is the result.




回答3:


i think you need the select event

$( ".selector" ).autocomplete({
   select: function(event, ui) { ... }
});

http://jqueryui.com/demos/autocomplete/#event-select



来源:https://stackoverflow.com/questions/8158246/firing-the-select-event-on-click-for-jquery-autocomplete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!