Reputation: 3857
I'm trying to search based on a school name, once the school name is selected populate a form.
I'm having a few issues searching on that particular jSON node, which in this case is name I have got the JSON response working, But it's just returning everything back. Not the specific term.
An example of my jSON Data :
[
{
"name":"The Mendip School",
"ta":"ta552023",
"address1":"Longfellow Road",
"address2":"Radstock",
"town":"",
"postcode":"BA3 3AL"
}
]
My jQuery is as follows :
// School Search....
var data_source = 'schools.json';
$(".school_name").autocomplete({
source: function ( request, response ) {
$.ajax({
url: data_source,
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response( $.map( data, function ( item )
{
return {
label: item.name,
value: item.name
};
}));
}
});
},
minLength: 3,
focus: function (event, ui) {
$(event.target).val(ui.item.label);
return false;
},
select: function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
}
});
How do I modify my JQuery to search on the name field? I will also need to get the other fields to populate input fields.
Thanks
Upvotes: 0
Views: 1302
Reputation: 755
Here is something that may suit your needs:
$("#school_name").autocomplete({
source: function ( request, response ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
$.getJSON("/schools.json?term=" + request.term, function (data) {
var x = $.grep(data, function (item, index) {
return matcher.test( item.name );
});
console.log(x);
response($.map(x, function (item) {
return {
label: item.name,
value: item.name
};
}));
});
}
The code above will filter the data using the regex(new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" )
). This regex will search for names which start-begin(^) with the typed text(by the user). The 'i' in the regex is for case-insensitive while the escapeRegex will just escape any special characters in user input.
You can also use your code and do the respective changes, I think it will also work. I just prefer to use $.getJSON. Take care of the #school_name for id(in your code you are using '.')
Try it here: http://jsbin.com/vawozutepu
Upvotes: 1