jQuery(document).ready(function($) { // !Handle displaying autocomplete data for each field $( '.vfb-post-tag' ).each( function(){ var form_id = $( this ).closest( 'form' ).find( 'input[name="form_id"]' ).val(), field_id = $( this ).attr( 'id' ).match( new RegExp( /(\d+)$/g ), '' ); $( '#' + $( this ).attr( 'id' ) ) // don't navigate away from the field on tab when selecting an item .bind( 'keydown', function( event ) { if ( event.keyCode === $.ui.keyCode.TAB && $( this ).data( 'autocomplete' ).menu.active ) event.preventDefault(); }) .autocomplete({ delay: 200, source: function( request, response ){ $.ajax({ url: VfbCreatePostAjax.ajaxurl, type: 'GET', async: true, cache: false, dataType: 'json', data: { action: 'vfb_create_post_tags', term: vfb_extractLast( request.term ), nonce: VfbCreatePostAjax.vfbCreatePostNonce }, success: function( data ){ response( $.map( data, function( item ){ return { value: item.value }; } )); } }); }, search: function() { // custom minLength var term = vfb_extractLast( this.value ); if ( term.length < 2 ) { return false; } }, focus: function() { // prevent value inserted on focus return false; }, select: function( event, ui ) { var terms = vfb_split( this.value ); // remove the current input terms.pop(); // add the selected item terms.push( ui.item.value ); // add placeholder to get the comma-and-space at the end terms.push( "" ); this.value = terms.join( ", " ); return false; } }); }); function vfb_split( val ) { return val.split( /,\s*/ ); } function vfb_extractLast( term ) { return vfb_split( term ).pop(); } });