javascript - how to make jquery autocomplete simplify -
i use jquery autocomplete
, code, call plugin, not good. there more simple way call jquery autocomplete
js
$(document).ready(function(){ $("#m_occupation").autocomplete("search/moccupation.php", { selectfirst: true }); $("#foccupation").autocomplete("search/f_occupation.php", { selectfirst: true }); $("#g_address").autocomplete("search/g_address.php", { selectfirst: true }); $("#relationship").autocomplete("search/relationship.php", { selectfirst: true }); });
what you've got isn't terrible. if you're ever initializing these autocompletes 1 time, it's pretty readable overall, although have repetition.
cache jquery objects future use. in snippet above, reference each jquery object (e.g.,
$("#m_occupation")
) once, in real webapp, there's pretty chance you'll use more. caching helps reduce number of jquery finding operations, , practice adopt though it's not increase performance user noticeably.cache options objects. you're repeating option declaration multiple times; declare single
autocompleteoptions
object , done it.refactor initialization function. if you're feeling autocomplete initialization ugly, or complex, or subject frequent edits, make single function. future global edits initialization can made 1 time rather multiple times.
a redo of code taking account like:
var initautocomplete = function($el, dataurl) { var autocompleteoptions = { selectfirst: true }; $el.autocomplete(dataurl, autocompleteoptions); }; $(document).ready(function(){ var $m_occupation, $foccupation, $g_address, $relationship; $m_occupation = $('#m_occupation'); initautocomplete($m_occupation, "search/moccupation.php"); $foccupation = $('#foccupation'); initautocomplete($foccupation, "search/f_occupation.php"); $g_address = $('#g_address'); initautocomplete($g_address, "search/g_address.php"); $relationship = $('#relationship'); initautocomplete($relationship, "search/relationship.php"); });
you technically optimize further using single string represent dom id , url gather data, in experience, breaks down in maintenance. wouldn't couple tightly.
Comments
Post a Comment