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);
});
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Feb 27, 2015 at 7:37
\$\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');
answered Oct 15, 2015 at 14:21
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.