Aaron Ward
Aaron Ward

Reputation: 57

jQuery Uncaught TypeError: Cannot read property 'text' of null

Problem: I am loading a modal form from an ajax call. Within the modal, I have a span element holding an email address. I am needing to capture the value of the span element in javascript. Currently, I have a button click that calls a function to obtain the text.

Code to read text: function AccountHistoryRedeemSendEmail(emailType) { clearNotifications(); console.log('Hit AccountHistoryRedeemSendEmail'); var url = "../../utility/account/ajaxAccountHistoryRedeemSendEmail.aspx"; var params = "eType" + emailType; //console.log($('#lblHRedeemEmailAddress')); console.log('Output text: ' + $('#lblHRedeemEmailAddress').text()); params += "&HRedeemEmailAddress=" + $("#lblHRedeemEmailAddress").text(); params += "&timestamp=" + new Date(); // new Ajax.Request( // url, // { // method: "get", // parameters: params, // onSuccess: parseAjaxResponseAccountHistoryRedeemSendEmail // } // ); }

The error being returned is: "Uncaught TypeError: Cannot read property 'text' of null "

I understand the error is telling me $('#lblHRedeemEmailAddress') is returning a null. Naturally, I have verified my element name to be correct. I have also inspected the element in chrome and verified it is present in the document. Here is html in the document:

<span id="lblHRedeemEmailAddress">[email protected]</span>

< img src="sendemail.jpg" id="SendEmail" alt="Email Certificate" onclick="AccountHistoryRedeemSendEmail('lblEmail');">

So, the question: Why is my lblHRedeemEmailAddress element null when I try to access it from the function? And, how do I fix this?

Upvotes: 1

Views: 7603

Answers (1)

David Hedlund
David Hedlund

Reputation: 129812

If lblHRedeemEmailAddress didn't exist, jQuery would return an empty result set, upon which you would still be able to call text. $ is probably referring to some other library, such as prototype.

Read up on noConflict or create a closure where $ is set to jQuery:

(function($) {
   // for anything in here, $ will be jQuery
})(jQuery);

Upvotes: 4

Related Questions