Jquery UI Autocomplete Extra Parameters and Autofill - A frustrated solution
Been looking into Jquery UI's Autocomplete (v1.8.5) and realized there is a sever lack of documentation on sending extra parameters and shooting extra data to autofill other fields. What I have works, but seriously, seems like such a hack... Any thoughts on how to improve this?
<script type="text/javascript">
var optofirst = {
width: 375,
// doing "$(this)" here fails
source: function( request, response ) {
// grab the calling element
// "$(this)" here works but ya gotta dig to get to the ID
var cat = $(this);
var callid = cat[0].element.context.id; //digging away
$.ajax({
// doing "$(this)" here fails
url: "automagic.php",
dataType: "json",
data: {
term : request.term,
//send its ID to the php script
grab : callid,
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
// start assigning item handles to the response
label: item.first,
value: item.first,
last: item.last,
}
}));
}
});
},
select: function( event, ui ) {
console.log( ui.item ?
"Selected: " + ui.item.last :
"Nothing selected, input was " + this.value);
// make #lname have the value last name
// the "item" in this case appears to get its info from the handles assign in "success:"
$("#flyover #lname").attr("value",ui.item.last);
},
minLength: 2,
};
开发者_JAVA技巧 $("#flyover #fname").autocomplete(optofirst);
</script>
You can use the source property. Set a function instead of an url. You should need only to edit url and replace customData line for as many custom properties you want to send to the server. For example:
$(this).autocomplete({
source: function(request, response) {
$.ajax({
url: 'data.php',
dataType: "json",
data: {
term : request.term,
customData : $('#something').val()
},
success: function(data) {
response(data);
}
});
},
minLength: 3}, {
});
The general idea looks good to me. Your code is pretty close to jQueryUI's custom data and display demo.
There are a few things you could improve on though:
// doing "$(this)" here fails
both inside the options object for autocomplete and your AJAX call, becausethis
in JavaScript does not make sense in object literals; it contains the context of a function call (see this question for a great explanation ofthis
);- Inside the
source
function,this
works because now there's a function around it.this
has a context. Instead of:
var callid = cat[0].element.context.id; //digging away
You could write:
var calid = this.element.attr('id');
This is because
this
in this case is already a jQuery object.$(this)
is redundant. Also, theelement
property is also a jQuery object, so you can just access theid
usingattr()
The rest looks ok to me. Have a look at the demo I referenced--it does some similar things to what you're trying to accomplish.
I really wanted to do this in rails 3.1 using coffeescript Heres a gist for it on github
精彩评论