I’m building a custom autocomplete for a search box on our site.
I’ve coded a keyup event handler to handle keyboard input for scrolling through the autocomplete list, having enter select elements/submit form, etc…
The problem I am having is I want an enter keypress to act as a the equivalent of a click on the element. However when the enter keypress calls the click method bound to the <p> tag, in Chrome, the click event handler can’t be found. In Firefox it works just fine.
Am I not allowed to bind click event listeners to <p> tags in Chrome? What’s going on? This works perfectly in Firefox.
Here is relevant code for the concrete examples:
I’ve bound the click event via jQuery’s live method to all list elements that are appended to my list during the autocomplete like so:
$('.suggestion .section li p').live( 'click', function (){
debugLog("a p tag was clicked");
$("#search-input").data('skip-hide', true);
$("#search .suggestion").data('selected-index', -1) ;
$("#search-input").val($(this).parent().data('search-text'));
$("#search-input").closest("form").submit();
});
Then a bit later I do this:
$("#search-input").keyup(function(event){
switch(event.keyCode )
{
case 13:
if($("#search .suggestion").data('selected-index') != undefined){
debugLog('a defined index was set when enter was pressed');
//THIS IS THE FAILING LINE IN CHROME
$("#search .suggestion li p")[$("#search .suggestion").data('selected-index')].click();
return false;
}
The html snippet that my autocompete fills out looks like this:
<form id="search-form" action="<?php echo $this->baseUrl(); ?>/search" method="get" accept-charset="utf-8">
<div id="search">
<input id="search-input" type="text" class="input-box input-focus" name="q" value="Enter a product or store..." /><input type="image" id="search-form-image" src="/images/nav-btn-search.gif" />
<div class="suggestion" style="display:none;">
<div class="section" id="stores-autocomplete">
<strong>Stores</strong>
<ul>
</ul>
</div>
<div class="section" id="searches-autocomplete">
<strong>Searches</strong>
<ul>
</ul>
</div>
<div class="section lastChild" id="coupons-autocomplete">
<strong>Coupons</strong>
<ul>
</ul>
</div>
</div>
</div>
</form>
Use
.eq()instead of[]to select the paragraph. Then, invoke.click()(as a jQuery method):When using square braces, you’re selecting a DOM element, and trying to invoke the DOM
.clickmethod. The solution involves using.eq(), so that a jQuery object is selected, so that jQuery’s.click(), aka.trigger('click'), method can be invoked.