开发者

How do you trigger autocomplete "select" event manually in jQueryUI?

I'm using jQueryUI autocomplete, and I have a function mapped to the select event, e.g.:

$("#someId").autocomplete({
    source: someData,
    select: function (event, ui) { ... },
    focus: function (event, ui) { ... }
});

I have开发者_Go百科 a special case: The user has focused on an item in the autocomplete drop-down (but not selected it) and I need to trigger the select event manually from a different function. Is this possible? If so, how?


Here's what worked for me:

$(this).data('ui-autocomplete')._trigger('select', 'autocompleteselect', {item:{value:$(this).val()}});


You could do:

$("#someId").trigger("autocompleteselect");


You can do it the way the jQuery team does it in their unit tests - see this answer


Simply call following function

setAutocomplete("#txt_User_Name","rohit");

function setAutocomplete(autocompleteId,valuetoset)
    {
        $(autocompleteId).val(valuetoset);
        $(autocompleteId).autocomplete("search", valuetoset);
        var list = $(autocompleteId).autocomplete("widget");
        $(list[0].children[0]).click();
    }


1 line solution

$('.ui-menu-item .ui-corner-all:contains(\"123")').autocomplete({autoFocus:true}).mouseenter().click()


$('#someId').data('uiAutocomplete')._trigger('select');


If we want to trigger search of something particularly:

$('#search-term').autocomplete('search', 'searching term');

or just

$('#search-term').autocomplete('search');

$('#search-term').autocomplete({
    ...
    minLength: 0, // with this setting
    ...
});


From outside:

$($('#someId').data('autocomplete').menu.active).find('a').trigger('click');

An example how to setup select triggering at pressing of horizontal arrows keys from inside of "open" autocomplete event:

$('#someId').autocomplete({
    open: function(event, ui) {
        $(this).keydown(function(e){
            /* horizontal keys */
            if (e.keyCode == 37 || e.keyCode == 39) {
               $($(this).data('autocomplete').menu.active).find('a').trigger('click');
            }
        });
    }
});

Unfortunately that nice way how to solve this marked as "success" did not work at my app in chromium 140.0.835.200


You don't have to go through a bunch of rigmarole to call select. This is how I call select from my own extended version of autocomplete.

$(this).data('ui-autocomplete').options.select(event, ui);

where I use this

/**
 * The jQuery UI plugin autocomplete
 */
$.widget( "ui.autocomplete", $.ui.autocomplete, {
   options: {
      close: function( event, ui ) {
         if (typeof event.currentTarget == 'undefined') {
            $(this).val("");
            $(this).data('ui-autocomplete').options.select(event, ui);
         }
      }
   }
 });


I found very simple way to make it work. Answers above did not work for me.

My input definition:

<div class="search_box">
<input type="text" class="inp disabled" id="search-user-id" placeholder="Search by user name or email" />
</div>

The autocomplete definition:

$('#search-user-id').autocomplete({
    minChars: 3,
    paramName: 'searchTerm',
    deferRequestBy: 200, // This is to avoid js error on fast typing
    serviceUrl: '${pageContext.request.contextPath}/settings/reset/psw/query',
    type: 'POST',
    onSelect : function(suggestion) {
        showUserData(suggestion.dto);
    }, 
    onSearchError: function (query, jqXHR, textStatus, errorThrown) {
        $('.cev-error-fields.reset-password').find('.error_msg').text(errorThrown).show().fadeOut(7000);
    }
}); 

Trigger it: I am triggering from an ajax defined in other page, I do not put the ajax here for simplicity. Inside the ajax response I just trigger it this way:

        $('#search-user-id').val(username);
        $('#search-user-id').focus();

It worked.


I stumbled upon this thread as I was seeking a way to prefill a bunch of jquery ui autocomplete fields in a form where users can modify an already submitted one.

First, I have to load the form, with some inputs using autocomplete.

Problem 1 : I created a php function able to call a premade autocomplete input, specifying some things like the input class, id, name... and value(s). I can also pass the name of a JS custom function to trigger (with the selected item's ID as a parameter), depending on the form and type of data... So I can't just "print" the prefilled input when loading the form because the custom function (and other actions specified in the built-in select: function( event, ui ) { ... } won't fire. I really need to mimic a search-->click action.

Problem 2 : the source comes from an ajax call performing a search from the string entered in the input. It then shows strings as items... but I want the real input to be the IDs of those sources. To do so, the select: event creates a hidden input with the ID of the clicked item, checks if it was already selected (I can select multiple elements from one autocomplete input..), etc. It has to be triggered. I really need to mimic a search-->click action.

Problem 3 : Since the source comes from an ajax call, I would have to make all these calls to prefill the form, which is a very bad way of populating a form (for various reasons). I can't really mimic the search-->click action.

Solution I simply created a second (hidden) autocomplete input for each "real ones", for which the initialisation $(id).autocomplete(...) performs the same actions (upon select), but is populated with static source i drew directly from the DB with the already saved input. Then, I simply mimic the search-->click in this dummy input, which draws the good inputs with the IDs I want to save...

foreach (values to prefill..) {
 $("#'.$mot_cle.'_input_autocomplete_prefill").val("'.$valeur_finale_unique['value'].'");
 $("#'.$mot_cle.'_input_autocomplete_prefill").autocomplete("search", "'.$valeur_finale_unique['value'].'");
 var list = $("#'.$mot_cle.'_input_autocomplete_prefill").autocomplete("widget");
 $(list[0].children[0]).click();
}

It's quite complicated. But in the end, everytime I want to show an autocomplete input in my pages, I only have to call the php function which wraps it up ;) And it's lightning fast, and don't mess with the input IDs\Names for the entire forms managing...

There is a lot going on backend, but in the end, it looks like this, when I enter this :

<div class="marge">
 <span class="texte_gras">Demandeur(s)</span><br>
 '.formulaire_autocomplete("demandeurs","pdrh_formulaire_ajouter_cible_valeurs","1","usager",$valeur_demandeur,"").'
</div>

PHP function formulaire_autocomplete($keyword(used for input name),$class(used for jquery serialize when submitting form),$multi(possibility to input more than one choice),$type(which DB table to search: users, courses, etc..),$value(IDs to prefill in the form for this input, if it is an already submitted form), $function(if I want to trigger a custom JS function when select:))

I get this :

<div class="marge">
                        <span class="texte_gras">Demandeur(s)</span><br>
                            <input style="width: 90%;" class="pdrh_formulaire_ajouter_cible_valeurs ui-autocomplete-input" type="text" name="demandeurs[]" id="demandeurs_input_autocomplete" value="" autocomplete="off">  <input style="width: 90%; display: none;" class="pdrh_formulaire_ajouter_cible_valeurs ui-autocomplete-input" type="text" name="demandeurs_prefill[]" id="demandeurs_input_autocomplete_prefill" value="" autocomplete="off">   <div id="demandeurs_boite_autocomplete_selection" style="width: 100%;"><div style="width: 100%;" id="demandeurs_auto_ID_25434"><div class="petite_marge"><input style="width: 80%;" class="pdrh_formulaire_ajouter_cible_valeurs" type="hidden" name="demandeurs_auto_ID[]" id="demandeurs_input_autocomplete_auto_id_25434" value="25434"><span class="petit_texte texte_gras">STEPHANIE (41263)</span><div class="bouton_transparent" onclick="effacer_div('demandeurs_auto_ID_25434')"><div class="petite_marge"><img src="./images/vide.png" style="width: 1em;"><img src="./images/effacer.png" style="width: 1em;"></div></div></div></div><div style="width: 100%;" id="demandeurs_auto_ID_18760"><div class="petite_marge"><input style="width: 80%;" class="pdrh_formulaire_ajouter_cible_valeurs" type="hidden" name="demandeurs_auto_ID[]" id="demandeurs_input_autocomplete_auto_id_18760" value="18760"><span class="petit_texte texte_gras">MARIE (23673)</span><div class="bouton_transparent" onclick="effacer_div('demandeurs_auto_ID_18760')"><div class="petite_marge"><img src="./images/vide.png" style="width: 1em;"><img src="./images/effacer.png" style="width: 1em;"></div></div></div></div></div><script>
                    $("#demandeurs_input_autocomplete").autocomplete({
                        source: function (request, response) {
                            requete_ajax = $.ajax({
                                type: "POST",
                                url: 'fonctions.php',
                                data: 'recherche_autocomplete=usager&chaine='+request.term,
                                dataType: 'json',
                                success: function(data) {
                                    ajax_en_cours = 0; console.log("Ajax terminé");
                                    // var resultat = JSON.parse(data.choix);
                                    var tableau_resultat = Object.values(data.choix);
                                    response(tableau_resultat);
                                    console.log(tableau_resultat);
                                },
                                error: function(e) {
                                    ajax_en_cours = 0; console.log("Ajax terminé");
                                    console.log('Erreur | demandeurs recherche autocomplete');
                                }
                            });
                        },
                        minLength: 3,
                        select: function( event, ui ) {
                            $("#demandeurs_input_autocomplete_auto_id").val(ui.item.ID);
                                var contenu_selection = $("#demandeurs_boite_autocomplete_selection").html();
                            $("#demandeurs_boite_autocomplete_selection").html(contenu_selection+"<div style=\"width: 100%;\" id=\"demandeurs_auto_ID_"+ui.item.ID+"\"><div class=\"petite_marge\"><input style=\"width: 80%;\" class=\"pdrh_formulaire_ajouter_cible_valeurs\" type=\"hidden\" name=\"demandeurs_auto_ID[]\" id=\"demandeurs_input_autocomplete_auto_id_"+ui.item.ID+"\" value=\""+ui.item.ID+"\"><span class=\"petit_texte texte_gras\">"+ui.item.value+"</span><div class=\"bouton_transparent\" onclick=\"effacer_div('demandeurs_auto_ID_"+ui.item.ID+"')\"><div class=\"petite_marge\"><img src=\"./images/vide.png\" style=\"width: 1em;\"><img src=\"./images/effacer.png\" style=\"width: 1em;\"></div></div></div></div>");
                            $("#demandeurs_input_autocomplete").val(" ");
                            
                        }
                    });
                        var valeurs_prefill = [{value: "STEPHANIE  (41263)", ID: "25434"},{value: "MARIE (23673)", ID: "18760"}];
                        $("#demandeurs_input_autocomplete_prefill").autocomplete({
                            source: valeurs_prefill,
                            minLength: 3,
                            select: function( event, ui ) {
                                $("#demandeurs_input_autocomplete_auto_id").val(ui.item.ID);
                                    var contenu_selection = $("#demandeurs_boite_autocomplete_selection").html();
                            $("#demandeurs_boite_autocomplete_selection").html(contenu_selection+"<div style=\"width: 100%;\" id=\"demandeurs_auto_ID_"+ui.item.ID+"\"><div class=\"petite_marge\"><input style=\"width: 80%;\" class=\"pdrh_formulaire_ajouter_cible_valeurs\" type=\"hidden\" name=\"demandeurs_auto_ID[]\" id=\"demandeurs_input_autocomplete_auto_id_"+ui.item.ID+"\" value=\""+ui.item.ID+"\"><span class=\"petit_texte texte_gras\">"+ui.item.value+"</span><div class=\"bouton_transparent\" onclick=\"effacer_div('demandeurs_auto_ID_"+ui.item.ID+"')\"><div class=\"petite_marge\"><img src=\"./images/vide.png\" style=\"width: 1em;\"><img src=\"./images/effacer.png\" style=\"width: 1em;\"></div></div></div></div>");
                            $("#demandeurs_input_autocomplete").val(" ");
                                
                            }
                        });
                            $("#demandeurs_input_autocomplete_prefill").val("STEPHANIE (41263)");
                            $("#demandeurs_input_autocomplete_prefill").autocomplete("search", "STEPHANIE (41263)");
                            
                                var list = $("#demandeurs_input_autocomplete_prefill").autocomplete("widget");
                                $(list[0].children[0]).click();
                            
                            
                        
                            $("#demandeurs_input_autocomplete_prefill").val("MARIE (23673)");
                            $("#demandeurs_input_autocomplete_prefill").autocomplete("search", "MARIE (23673)");
                            
                                var list = $("#demandeurs_input_autocomplete_prefill").autocomplete("widget");
                                $(list[0].children[0]).click();
                            
                            
                            </script>
                    </div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜