jquery - trigger event on selecting item from datalist, not when typing -
i have form this:
<input list='data-list' id='list'> <datalist id='data-list'> <option>first</option> <option>second</option> </datalist>
the user can select item datalist -or- can type in it's own value. connection database through json call php script fill in other information in rest of form. want trigger when user typed name in list-input (so when content blurred) or when user clicked option datalist.
using $( ':input#list' ).on( 'change', function...
function triggered when input loses focus, when item data-list selected waits 'till input loses focus, want event fire straight away
using $( ':input#list' ).on( 'input', function...
clicking item datalist triggers function straight away, want, typing trigger event well, each keystroke, sending lot of unwanted requests php script.
i have tried binding event datalist directly, didn't work.
i looking trigger function when user clicks (or uses keyboard select) item datalist or when user entered word , moves next input.
the solution went combination of both events...
i keep track of variable window.latest_autofill_qeury
prevent loading same thing twice in row. have following onchange
function, triggers when user puts focus out of input (tabs out, or clicks elsewhere)
$( ':input#list' ).on( 'change', function(){ var current = $( ).val(); if( window.latest_autofill_query != current ) load_autofill(); } );
then there's function keeps track of user types, , checks if value entered in datalist. if so, assume that's user wants , next datalist queried. triggered when user clicks item datalist result in value of input being present in datalist , triggering load_autofill:
$( ':input#list' ).on( 'input', function(){ var current = $( ).val(); $( 'datalist#data-list option' ).each( function(){ if( $( ).text() == current ){ load_autofill(); return false; //* break out of jquery each loop } ); } );
the load_autofill
function keeps track of loaded last prevent double loads. won't go details of load_autofill 'cause it's application specific, framework this:
function load_autofill(){ var current = $( ':input#list' ).val(); window.latest_autofill_query = current; //* ... perform loading of next datalist }
now next datalist loaded user selected item datalist, not after every keystroke user makes, when text entered present in datalist.
Comments
Post a Comment