At first, I thought this should be very easy. Just use $(selector).val() to get the value.
However, I got a lot of difficulties.
Allow me to make an example.
Assume that I have two text boxes, and they are attached to jQuery’s AutoComplete plugin.
When I click on the first textbox, I make ajax call, when success, I bind the returned data into that clicked textbox, and a hiddenField, which is used to hold the returned ID.
The whole progress is easy, I make the ajax call and goes successful. The hiddenField now has some returned value.
When I create a second autocomplete event, and for this one, I am trying to read the value from the hidden box.
This time, failed. Not because of the ajax call, but because the value is null…
I am confused. Because the hiddenField does have some value there. But why I cannot read it easily?
Here is some codes I have
function DepartCityAutoComplete() {
$("#txtDeparture").autocomplete({
minLength: 3,
source:
function (request, response) {
$.ajax({
type: "POST",
url: "/AjaxDataServices.asmx/DepartCityAutoComplete",
data: '{"keyword":"' + request.term + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
return { value: item.CityName + ", " + item.StateShortName, id: item.CityID }
}))
},
error: function () {
alert("An unexpected error has occurred during processing.");
}
});
},
select: function (event, ui) {
$("#txtDeparture").val(ui.item.value);
$("#hiddenDepartCityID").val(ui.item.id);
}
});
}
function DestCityAutoComplete() {
var departCityID = $("hiddenDepartCityID").val();
$("#txtDestination").autocomplete({
minLength: 3,
source:
function (request, response) {
$.ajax({
type: "POST",
url: "/AjaxDataServices.asmx/DestCityAutoComplete",
data: '{"keyword":"' + request.term + '","id":"' + departCityID + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
return { value: item.CityName + ", " + item.StateShortName, id: item.CityID }
}))
},
error: function () {
alert("An unexpected error has occurred during processing.");
}
});
},
select: function (event, ui) {
$("#txtDestination").val(ui.item.value);
$("#hiddenReturnCityID").val(ui.item.id);
}
});
}
Can anyone give me any suggestion? Thank you very much.
Here is my guess
It is because of the $(document).ready(function ()
I have the following code:
$(document).ready(function () {
DepartCityAutoComplete();
DestCityAutoComplete();
});
So these two functions are inited when the page is loaded.
Even though the first autoComplete function assigns some value into the hiddenField, the web browser doesn’t know it.
Please correct me if I am wrong. Thanks
shouldn’t this be