How to not repeat code in select function of Jquery UI autocomplete feature
I have two jquery ui autocomplete boxes on a large form (probably with 40 or more fields). The user can search two ways using two different autocomplete boxes (either by name or an account number). I am populating the other fields on the form when the user selects his search result. However, I was wondering if there was a cleaner way to do 开发者_如何学Goit.
Currently, this is what I have.
$( "#search-by-custname" ).autocomplete({
source: "cust_search_by_name.php",
minLength: 4,
select: function(event, ui){
$('#Custid').val(ui.item.Custid);
$('#Alpha1').val(ui.item.Alpha1);
$('#CustName').val(ui.item.CustName);
}
});
$( "#search-by-custalpha1" ).autocomplete({
source: "cust_search_by_alpha1.php",
minLength: 4,
select: function(event, ui){
$('#Custid').val(ui.item.Custid);
$('#Alpha1').val(ui.item.Alpha1);
$('#CustName').val(ui.item.CustName);
}
});
The php files are grabbing data from a remote data source, and everything works ok.
The problem is, if I reference all of those fields twice inside of each autocomplete box, that will be a lot of lines of code... I was wondering if there was a cleaner way to do it.
I played around with writing my own function, but, I'm a noob to javascript and jquery.
I'm not 100% sure this will work but I can't see why it wouldn't.
var selectFunc = function(event, ui){
$('#Custid').val(ui.item.Custid);
$('#Alpha1').val(ui.item.Alpha1);
$('#CustName').val(ui.item.CustName);
};
$( "#search-by-custname" ).autocomplete({
source: "cust_search_by_name.php",
minLength: 4,
select: selectFunc
});
$( "#search-by-custalpha1" ).autocomplete({
source: "cust_search_by_alpha1.php",
minLength: 4,
select: selectFunc
});
精彩评论