Pat Pat - 2 years ago 85
jQuery Question

JQuery Autocomplete not working on button/link click

I have below code, which is calling jquery JSON autocomplete on button click. It is working as expected only for the very first time, autocomplete is called when i click the commandlink, but next time the autocomplete is triggered when i started typing in the text box (before i click on the command link). It works again when i refresh the page- autocomplete called only when link clicked.

<ui:component>
<tr:panelGroupLayout>
<tr:inputText id="#{id}" value="#{value}">
</tr:inputText>

<tr:commandLink id="idGlobalTrigger" partialSubmit="true">
<tr:image source="/resources/images/tick_light.gif"></tr:image>
</tr:commandLink>
</tr:panelGroupLayout>
<script>
$("#idGlobalTrigger").click(function() {
/*text box id */
var jqueryObj = "#"+"#{id}";
$(jqueryObj).autocomplete({
source : function(request, response) {
$.ajax({
type : "GET",
url : "#{facesContext.externalContext.requestContextPath}/GlobalServlet",
data : {
term : request.term
},
dataType : "json",
success : function(
data) {
response(data);
},
error : function(
XMLHttpRequest,
textStatus,
errorThrown) {
// alert('Error1'+textStatus +textStatus);
}
});
}
});

$(jqueryObj).focus();
$(jqueryObj).autocomplete("search");
});
</script>
</ui:component>

Pat Pat
Answer Source

I reinitialize the autocomplete on select event. This resolves my issue.

$(jqueryObj).on("autocompleteselect", function(event,ui) {          
        $(jqueryObj).autocomplete({
            source : null,
            response: function( event, ui ) {
                ui.content.push({value:'', id:0, label:''});
            } 
        }); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download