I took most of this code from jQuery UI documentation.
I want to add to the request variables such that the <input> id is also sent.
Input looks like this:
<input size="50" class="attr_values" name="msrp" id="msrp" />
Now here’s the jquery. Inside of .autocomplete source $.getJSON I try to use “this.id” and it doesn’t work. How can I get this to work?
$(document).ready(function() {
// 2 string parsing functions
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( '.attr_values' )
// don't navigate away from the field on tab when selecting an item
.bind( 'keydown', function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( 'autocomplete' ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( 'controllers/core_data/ajax/core_data.php', {
'attr_name' : this.id, // THIS DOESN'T WORK
'term': extractLast( request.term )
}, response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
// var attr_name = this.id;
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( '' );
this.value = terms.join( ', ' );
return false;
}
});
});
Also note that I have applied this to the “.attr_values” class rather than to one particular id like the examples show. I have a whole bunch of fields, each with a different id. That’s why I need to send the id AND term to the php script. So that it knows which table to look the term up in.
thisdoesn’t refer to the original collection anymore inside thegetJSONcallback. Try drilling upward to get to the original element:The context
thishere refers to theautocompleteobject that you are evaluating thesourcefunction for. We can use theelementproperty to get the corresponding jQuery collection, and then find the id from that.