Retrieve value of element on dom on page reload
I have the following JavaScript function which is used to keep users from inundating our server with Ajax requests:
var validateZip = function () {
var lastSuccessful = parseInt(jQuery('#mailingZip').val(), 10);
return {
开发者_运维百科validate: function(zip) {
var is5DigitNumber = /^\d{5}$/;
if (is5DigitNumber.test(zip) && lastSuccessful !== zip) {
lastSuccessful = zip;
return true;
} else {
return false;
}
}
}();
This page is reloaded if users input a bad zip code or other errors appear on the form. However since the dom hasn't loaded yet, I always pull NaN from that field.
Placing it in the on document ready for jQuery means that I can't call the function directly.
How can I modify my scope such that the lastSuccessful will remain "private" and get the value once the dom is ready?
function validateZip() { // use function declaration, not function expression
var lastSuccessful = parseInt(jQuery('#mailingZip').val(), 10);
return {
validate: function(zip) {
var is5DigitNumber = /^\d{5}$/;
if (is5DigitNumber.test(zip) && lastSuccessful !== zip) {
lastSuccessful = zip;
return true;
} else {
return false;
}
}
}; // removed premature invocation of function
jQuery(validateZip); // call it on document ready instead
Why can't you call it in ready event? Of course you can enclose it into another function:
$(functon(){
var validateZip = function () {
var lastSuccessful = parseInt(jQuery('#mailingZip').val(), 10);
return {
validate: function(zip) {
var is5DigitNumber = /^\d{5}$/;
if (is5DigitNumber.test(zip) && lastSuccessful !== zip) {
lastSuccessful = zip;
return true;
} else {
return false;
}
}
}();
});
The question is you you need to keep validateZip
function as defined global? If you only run it at this point, just omit its declaration and just write:
$(functon(){
(function () {
var lastSuccessful = parseInt(jQuery('#mailingZip').val(), 10);
return {
validate: function(zip) {
var is5DigitNumber = /^\d{5}$/;
if (is5DigitNumber.test(zip) && lastSuccessful !== zip) {
lastSuccessful = zip;
return true;
} else {
return false;
}
}
})();
});
Don't know why I didn't think / do this before. I created a getter/setter on my return function, then on the document ready just called the setter with that value.
var validateZip = function() {
// Track the last sent in zip code -- treat this as private data
var lastSuccessful = "";
return {
validate : function(zip) {
var is5DigitNumber = /^\d{5}$/;
if (is5DigitNumber.test(zip) && lastSuccessful !== zip) {
lastSuccessful = zip;
return true;
} else {
return false;
}
},
setLastSuccessful : function(zip) {
lastSuccessful = zip;
},
getLastSuccessful : function() {
return lastSuccessful;
}
}
}();
jQuery(document).ready( function() { validateZip.setLastSuccessful(jQuery('#mailingZip').val()); });
精彩评论