1
\$\begingroup\$

This jQuery actually autocomplete when the onkeydown class is present and load the autocomplete with corresponding variable. This is working but I want to make it shorter.

var autocomp_opt = { source: "<?php echo base_url();?>description/get_description", minLength: 1, select: function(evt, ui) { this.form.sub_description.value = ui.item.sub_description; } }; var autocomp_opt1 = { source: "<?php echo base_url();?>description/get_description", minLength: 1, select: function(evt, ui) { this.form.sub_description2.value = ui.item.sub_description; } }; $(document).on("keydown", ".sn", function () { $(this).autocomplete(autocomp_opt); }); $(document).on("keydown", ".sn2", function () { $(this).autocomplete(autocomp_opt1); }); 
\$\endgroup\$
2
  • \$\begingroup\$ this.form.sub_description.value AND this.form.sub_description2.value is different. Should wrap the code into function \$\endgroup\$ Commented Feb 27, 2015 at 7:43
  • \$\begingroup\$ Agree with @NorlihazmeyGhazali, please see my implementation below. \$\endgroup\$ Commented Oct 15, 2015 at 14:24

1 Answer 1

1
\$\begingroup\$

I'm proposing to reduce code by putting all similar code to one function:

function initAutocomplete(selector, field) { $(selector).on('keydown', function() { $(this).autocomplete({ source: '<?php echo base_url();?>description/get_description', minLength: 1, select: function(evt, ui) { this.form.elements[field].value = ui.item.sub_description; } }); }); } initAutocomplete('.sn', 'sub_description'); initAutocomplete('.sn2', 'sub_description2'); 
\$\endgroup\$

You must log in to answer this question.