简体   繁体   中英

jquery autocomplete .When you have the autocomplete and press 'enter',i do not want to search ,actually it will do search

input autocomplete ,you press the 'enter' key , i do search something.But when you have the autocomplete and press 'enter',i do not want to search ,actually it will do search when you press 'enter' ,Because it will capture the enter event and execute the search function.

this is first function: the autocomplete code:

$('input[name=fieldInputName]').autocomplete(names, {
         max: max,    
         minChars: minChars ,   
         width: 149,     
         scrollHeight: 500,   
         matchContains: true,    
         autoFill: false, 
         sortable: true,
         matchSubset :false,
         formatItem: function(row, i, max) {
             return  row[returnSearchkey];
         },
         formatMatch: function(row, i, max) {
             return row[returnSearchkey] ;
         },
         formatResult: function(row) {
            return row[returnSearchkey];
         }
     }).result(function(event, row, formatted) {

     });

this is second function: the pressenter code that will do search:

function pressEnter(e){
        e = e || event;
        if (e.keyCode == 13) {
        submitSearch()();
        }
} 

The Html of input :

 <input onkeyup="pressEnter(event);"type='text' name='createdBy' />

When you trigger the autocomplete and select one items by press 'enter' ,it will do the autocomplete and fill back the selected value,but it will also invoke the second function "pressEnter(e)" .In fact I want to press enter when you triggered the autocomplete but not to execute the second function(pressEnter).

The events in a DOM start somewhere in your tree going down to the element (capturing phase) and then they bubble up the DOM (bubbling phase).

You can catch the event and stop it from propagating. It wont be propageted further then and wont call other event handlers (like your second function) which are attached to eg wrapping elements.

In the event handler of the autocomplete you should call stopPropagation() on the event. Altough this doesnt work in all browsers. In IE prior to IE9 the method is called cancelBubble(true) .

In order to prevent a browsers default behaviour you can do event.preventDefault()

You can read more on this by searching "Event Cancellation" or "Event Propagation", as this is a tricky topic in JavaScript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM