I’m unable to get this jquery statement to work on page load but it works once when I refresh F5 the page.
<div id="ResultsDiv"></div>
<div id="pager" class="pager"></div>
<input id="HfId" type="hidden" />
<script type="text/javascript">
var itemsPerPage = 5;
$(document).ready(function() {
getRecordspage(0, itemsPerPage);
var maxvalues = $("#HfId").val();
alert(maxvalues);
$(".pager").pagination(maxvalues, {
callback: getRecordspage,
current_page: 0,
items_per_page: itemsPerPage,
num_display_entries: 5,
next_text: 'Next',
prev_text: 'Prev',
num_edge_entries: 1
});
});
</script>
On the initial pageload alert(maxvalues); is nothing. However when I refresh it shows the value of maxvalues which is in the hidden field HfId because it is assigned in the function getRecordspage.
Why this strange behaviour…. Any suggestion…
EDIT:
function getRecordspage(curPage) {
$.ajax({
type: "POST",
url: "Default.aspx/GetRecords",
data: "{'currentPage':" + (curPage + 1) + ",'pagesize':5}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(jsonObj) {
$("#ResultsDiv").empty();
$("#HfId").val("");
var strarr = jsonObj.d.split('##');
var jsob = jQuery.parseJSON(strarr[0]);
var divs = '';
$.each(jsob.Table, function(i, employee) {
divs += '<div class="resultsdiv"><br /><span class="resultName">' + employee.Emp_Name + '</span><span class="resultfields" style="padding-left:100px;">Category :</span> <span class="resultfieldvalues">' + employee.Desig_Name + '</span><br /><br /><span id="SalaryBasis" class="resultfields">Salary Basis :</span> <span class="resultfieldvalues">' + employee.SalaryBasis + '</span><span class="resultfields" style="padding-left:25px;">Salary :</span> <span class="resultfieldvalues">' + employee.FixedSalary + '</span><span style="font-size:110%;font-weight:bolder;padding-left:25px;">Address :</span> <span class="resultfieldvalues">' + employee.Address + '</span></div>';
});
$(".pager").pagination(strarr[1], {
callback: getRecordspage,
current_page: 0,
items_per_page: 5,
num_display_entries: 5,
next_text: 'Next',
prev_text: 'Prev',
num_edge_entries: 1
});
$("#ResultsDiv").append(divs);
$(".resultsdiv:even").addClass("resultseven");
$(".resultsdiv").hover(function() {
$(this).addClass("resultshover");
}, function() {
$(this).removeClass("resultshover");
});
$("#HfId").val(strarr[1]);
}
});
}
Your
getRecordspagefunction is asynchronous. It makes an Ajax call which, when it completes, sets the value you are trying to read. However, you are not waiting for the call to complete before reading the value.