I am trying to use bootstrap typeahead.
I am having trouble handling which item has been selected.
Below is the code I have so for
var bindto = $(".search.typeahead");
bindto.typeahead({
source: function (query, response) {
var map = {};
var advicesearchList = [];
return $.ajax({
url: "/Advice/AutoComplete",
type: "GET",
cache: false,
data: { querystring: query },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function (i, result) {
map[result.Title] = result;
advicesearchList.push(result.Title);
});
response(advicesearchList);
}
});
}
}).on("typeahead:selected", function (e, o) {
console.log("item selected");
});
What would be the correct way to detect what the user has selected from one of the items in the list
thanks
Try using the afterSelected option:
var bindto = $(".search.typeahead");
bindto.typeahead({
source: function (query, response) {
//your code...
}, afterSelect: function (data) {
//print the data to developer tool's console
console.log(data);
}
});
Docs
Related
I want to split the ajax returned values using jQuery.
Here is my code:
var url = "/StudentProgress/GetStudProgDet/";
$.ajax({
url: url,
data: { currentAcadYr: iAcademicYearText, currentSem: iSemesterText },
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "GET",
success: function (data) {
var result = $(data).text().split(':');
var ProgAcadYearCode = result[0].ProgAcadYearCode;
var productSize = result[1];
// alert(data.ProgAcadYearCode);
//$("#ToProgressAcademicYearId option").filter(function () {
// return this.text == testsem;
//}).attr('selected', true);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
I got a result like this:
data = {
success: true,
progAcadYearCode: 20172018,
progAcadYearId: 17,
progressSemId: 47,
progressSemNo: 2
}
How do I extract the desired values from the JSON using jQuery?
Based on data what you shown,you have to directly fetch it's properties like below:-
success: function (data) {
console.log(data.success);
console.log(data.progAcadYearCode); //and so on
},
I have an autocomplete text field, that uses JSON like so:
$(function () {
var src = '#Url.Action("GetParts", "Parts")'
$("#autoCompleteBox").autocomplete({
source: function (request, response) {
$.ajax({
url: src,
async: true,
dataType: "json",
data: {
partNumber: $("#autoCompleteBox").val()
},
success: function (data) {
response(data[0]);
}
});
}
});
});
What I want to do is when the user selects the item from the suggested list is make another ajax call to get specific information about that item and populate other textboxes on the page.
What is the best approach for this?
You can do that in the select event of the autocomplete.
$(function () {
var src = '#Url.Action("GetParts", "Parts")'
$("#autoCompleteBox").autocomplete({
source: function (request, response) {
$.ajax({
url: src,
async: true,
dataType: "json",
data: {
partNumber: $("#autoCompleteBox").val()
},
success: function (data) {
response(data[0]);
}
});
},
select: function (event, ui) {
var item= ui.item.label;
//Now make the ajax call here
$.post("SomeValidUrl", new { id : item } ,function(res){
// do something with res
});
}
});
});
I have a set of cascading-option dropdown boxes that I'm trying to populate via javascript & jquery. In the $(document).ready section I'm trying to implement the jquery .done() function to ensure that each prior function is completed before the next run starts running, but it doesn't seem to be working:
$(document).ready(function () {
$.when(getSchoolYears()).done(function () {
$.when(getDistricts()).done(function () {
$.when(getAreas()).done(function () {
$.when(getSchoolTypes()).done(function () {
$.when(getSchoolLevels()).done(function () {
$.when(getGrades()).done(function () {
$.when(getEvents()).done(function () {
$.when(getResolutions()).done(function () {
$.when(getSchools()).done(function () {
loadCharts();
})
})
})
})
})
})
})
})
})
})
Focusing on the first two functions, getSchoolYears() & getDistricts(), I put consle.log statements into these functions, and the message for getDistricts() gets logged before the message for getSchoolYears()
function getSchoolYears() {
var data = [];
var param = {};
$.ajax({
type: "POST",
contentType: "application/json; charset=UTF-8",
url: "../WebServices/myLocations.asmx/get_SchoolYears",
data: JSON.stringify(param),
dataType: "json",
success: function (msg) {
var data = [];
data.push(msg.d);
$('#ddSchoolYear li').remove();
for (var i = 0; i <= data.length; i++) {
$('#ddSchoolYear').append(data[i]);
}
$('#hidSchoolYear').val(ddSubmitted('#ddSchoolYear input', '#lblYear'));
console.log('finished');
}
});
}
function getDistricts() {
console.log($('#hidSchoolYear').val());
var param = { "endYear": $('#hidSchoolYear').val() };
return $.ajax({
type: "POST",
contentType: "application/json; charset=UTF-8",
url: "../WebServices/myLocations.asmx/get_Districts",
data: JSON.stringify(param),
dataType: "json",
success: function (msg) {
var data = [];
data.push(msg.d);
$('#ddDistrict li').remove();
for (var i = 0; i <= data.length; i++) {
$('#ddDistrict').append(data[i]);
}
}
});
}
Am I not understanding how the .done() function works? Is there a way to ensure that one functions completes before the next one begins?
Controller Action:
[HttpGet]
public JsonResult CriteriasForAward(int awardId)
{
var criteriaList = _awardService.GetCriteriasForAward(awardId);
return Json(new { data = criteriaList }, JsonRequestBehavior.AllowGet);
}
Ajax Call:
<script>
jQuery(document).ready(function () {
$("#Award").change(function () {
var selectdAward = $("#Award").val();
alert("Id" + selectdAward);
var ServiceUrl = "/Nomination/CriteriasForAward?awardId=" + selectdAward;
$.ajax({
type: 'GET',
url: ServiceUrl,
contentType: "application/json; charset=utf-8",
error: function (xhr, err) {
alert(xhr.responseText)
},
success: function (data)
{
debugger;
$.each(data, function (key, val) {
alert(key);
});
}
});
});
});
</script>
All the things are going good..Also ajax call is succeeded,the data field contain array of all objects returned by ajax but when i wanted to alert key of each item for testing then it alerts undefined for only once..
If i debug it in browser then it contains values as shown in snapshotenter image description here
Try this:
$.ajax({
type: 'GET',
url: ServiceUrl,
contentType: "application/json; charset=utf-8",
error: function (xhr, err) {
alert(xhr.responseText)
},
success: function (data)
{
debugger;
$.each(data.data, function (key, val) {
alert(key);
});
}
});
by Json(new { data = criteriaList }); you creating new Json object that have data property. So if you want to access to that, just add .data: data.data, or change the json property name, to make more readable.
In your response data is object so you have to call just like that
$.each(data.data, function (key, val) {
alert(key);
});
There is another way to achieve this you have to send json_encode from controller.
When I preload values into Select2 dropdown, and expand the control to type in a value. It filters the preloaded values. How do I configure Select2 to make ajax calls (new search) when I type in the text box? If I don't preload values into Select2, the ajax calls work. So how can I have both?
I preload my select2 control with something like this:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: url,
data: json,
dataType: "json",
success: function (data, textStatus) {
var json = JSON.parse(data.d);
var arrData = [];
if (json !== null && json !== undefined) {
if (json.length > 0) {
$.each(json, function (index, element) {
var item = { id: element.CommonName, text: element.CommonName, name: element.CommonName };
arrData.push(item);
});
}
}
$("[ID$=ddlDropDown]").select2({
data: arrData
});
}
});
I instantiate my Select2 control with this:
$("[ID$=ddlDropDown]").select2({
ajax: {
url: url,
type: "POST",
dataType: 'json',
async: true,
contentType: "application/json; charset=utf-8",
delay: 500,
data: function (params) {
var query = {
searchString: (params.term || ""),
page: params.page
}
// Query paramters will be ?search=[term]&page=[page]
return JSON.stringify(query);
},
processResults: function (data, page) {
var json = JSON.parse(data.d);
if (json != null) {
if (json.length > 0) {
return {
results: $.map(json, function (item) {
return {
text: item.CommonName,
name: item.CommonName,
id: item.CommonName
}
})
};
} else {
return false;
}
}
else {
return false;
}
},
success: function (data, page) {
$("[ID$=ddlDropDown]").select2("data", data, true);
}
},
minimumInputLength: 2,
placeholder: "Select a Value",
disabled: false,
cache: true
});
as i had this problem and could not found any solution, I would like to share a solution which i did.even this is an old question which is not answered yet.would be helpful for others
$('#select2').select2({
allowClear: true,
multiple: false,
// minimumInputLength: 3,
ajax: {
url: "url",
dataType: 'json',
delay: 250,
type: 'POST',
data: function (params) {
return {
q: params.term, // search term
};
},
processResults: function (data, container) {
return {
results: $.map(data, function (item) {
return {
text: item.title + '| <b>' + item.title_2 + '</b>',
id: item.id,
}
})
};
},
cache: false
},
escapeMarkup: function (markup) {
return markup;
},
placeholder: __('select.project_search'),
}).live('change', function (e) {
// on change code
});
And in your controller you can check
if search term is null then return the preload options
else run the SQL for search data or return remote data.
the trick is you have to comment out minimumInputLength
this will trigger select2 ajax whenever you click it. and loads preload for you like following
and when you search you will get remote results like this
I hope this will help someone searching for a solution