I am a beginner using jQuery AutoComplete in a search box on my Index page:
JS:
<script type="text/javascript">
$(document).ready(function () {
$('#searchName').autocomplete({
source: '@Url.Action("GetUsers", "Home")'
});
});
</script>
HTML:
<div id="searchbox" style="float:left;">@Html.TextBox("searchName", null, new { @placeholder = "Name" })
Controller:
public JsonResult GetUsers(string term)
{
Context db = new Context();
List<string> users;
.
.
.
return Json(users, JsonRequestBehavior.AllowGet);
}
Right now, the Autocomplete is working, but my question is how can I hookup a drop-down that changes the source of the autocomplete to a different function, where a different set of users is searched?
In other words, I need the source of the Autocomplete function to change based on the value selected from a drop-down.
Is this possible?
Thank You!
You can specify a function for the source option: http://api.jqueryui.com/autocomplete/#option-source
Using this approach, you would update the javascript so that you have more control of the GET call so you can pass in a second parameter:
<script type="text/javascript">
$(document).ready(function () {
$('#searchName').autocomplete({
source: function (request, response) {
jQuery.get('@Url.Action("GetUsers", "Home")', {
term: request.term,
otherId: $('#otherDdl').val()
}, function (data) {
response(data);
});
}
});
});
</script>
Then on the server you can check the passed in otherId
and based on that change the source.
public JsonResult GetUsers(string term, int otherId)
{
Context db = new Context();
List<string> users;
if(otherId == ???)
// Default search
else
// Search alternate location
.
.
.
return Json(users, JsonRequestBehavior.AllowGet);
}
The autocomplete source
accepts a callback function use that to build your data based on dropdown value eg :
if(dropdown.val() == 1){
// hard-coded - get from external source
var data = [{ "label": "test1", "value": "test1" },
{ "label": "test2", "value": "test2" },
{ "label": "test3", "value": "test3" } ];
} else{
....
}
Then in the autocomplete source assign it to response:
source: function (request, response) {
response(data);
},
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.