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\$

migrated from stackoverflow.com Mar 2 '15 at 14:00

This question came from our site for professional and enthusiast programmers.

  • \$\begingroup\$ this.form.sub_description.value AND this.form.sub_description2.value is different. Should wrap the code into function \$\endgroup\$ – Norlihazmey Ghazali Feb 27 '15 at 7:43
  • \$\begingroup\$ Agree with @NorlihazmeyGhazali, please see my implementation below. \$\endgroup\$ – Valentin Oct 15 '15 at 14:24
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\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy