I want to set values for objects after the DOM has loaded completely. Problem is, I'm getting a null pointer exception after calling a OnBlur and OnFocus event from a textbox. What am I doing wrong?
javascript:
$(document).ready(function () {
var sumThursdayHrs = $('span[id*="lblThursdayHrs"]').last()
});
var tempThursdayHrs = 0.0;
function BlurThursdayHrs(sender, args) { sumThursdayHrs.text(tempThursdayHrs + sender.get_value()); }
function FocusThursdayHrs(sender, args) { tempThursdayHrs = sumThursdayHrs.text() - sender.get_value(); }
markup:
<telerik:RadNumericTextBox ID="txtThursdayHrs" runat="server" NumberFormat-DecimalDigits="1"
Width="25px" MinValue="0" Type="Number" DbValue='<%# Eval("ThursdayHrs") %>'>
<ClientEvents OnBlur="BlurThursdayHrs" OnFocus="FocusThursdayHrs" />
</telerik:RadNumericTextBox>
error:
Microsoft JScript runtime error: 'sumThursdayHrs' is undefined
As you said in the heading, the values are set in a function (the ready-event-handler function). But JavaScript has function scope, and as you declared sumThursdayHrs to be a local (not to say "private") variable by using the var keyword, it is undefined from outside. Two possibilites:
if you are using jquery already why not bind the events with jquery?
$('span[id$="txtThursdayHrs"]:first').on("focus", FocusThursdayHrs)
.on("blur", BlurThursdayHrs);
Also, declare those function inside the doc ready function, so they can access sumThursdayHrs, or use anonymous functions in the same place instead of calling the functions
Ex:
$(document).ready(function () {
var sumThursdayHrs = $('span[id*="lblThursdayHrs"]').last();
var tempThursdayHrs = 0.0;
$('span[id$="txtThursdayHrs"]:first').on("focus", function() {
sumThursdayHrs.text(tempThursdayHrs + $(this).val());
})
.on("blur", function() {
tempThursdayHrs = sumThursdayHrs.text() - $(this).val();
});
});
Or move sumThursdayHrs to a global object... For sanity's sake, I recommend not putting it in window though.
Instead define a global namespace to hold your app specific global variables. This is called global abatement.
Ex.
var MyApp = {};
$(document).ready(function () {
MyApp.sumThursdayHrs = $('span[id*="lblThursdayHrs"]').last();
//...
--
MyApp.tempThursdayHrs = 0.0;
function BlurThursdayHrs(sender, args) { MyApp.sumThursdayHrs.text(MyApp.tempThursdayHrs + sender.get_value()); }
function FocusThursdayHrs(sender, args) { MyApp.tempThursdayHrs = MyApp.sumThursdayHrs.text() - sender.get_value(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With