\$\begingroup\$
\$\endgroup\$
2
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
coolshoxcoolshox
-
\$\begingroup\$ this.form.sub_description.value AND this.form.sub_description2.value is different. Should wrap the code into function \$\endgroup\$Norlihazmey Ghazali– Norlihazmey Ghazali2015年02月27日 07:43:01 +00:00Commented Feb 27, 2015 at 7:43
-
\$\begingroup\$ Agree with @NorlihazmeyGhazali, please see my implementation below. \$\endgroup\$Valentin Podkamennyi– Valentin Podkamennyi2015年10月15日 14:24:41 +00:00Commented Oct 15, 2015 at 14:24
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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
default