I have the following simple function to replace all commas in a string and put the new value in place of the user entered value. This works great when called on a blur event.
$(document).ready(function () { $(document).on('blur change', '.string input', test); function test() { var i = ''; i = $('.string input').val(); i = i.replaceAll(',', ''); $('.string input').val(i); } String.prototype.replaceAll = function(str1, str2, ignore) { return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2); } });
However if I wanted to just call the function on form load instead of blur event (say if a value already exists in the field, even though this the ReplaceAll function accepts and returns blank values as well). Here is the code I would use. Doing this causes all javascript to fail on the ReplaceAll step. Why is this?
THIS FAILS @ i = i.replaceAll(',', '');
$(document).ready(function () { test(); function test() { var i = ''; i = $('.string input').val(); i = i.replaceAll(',', ''); $('.string input').val(i); } String.prototype.replaceAll = function(str1, str2, ignore) { return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2); } });
Even if I try to copy the code out of the function and run it on form load it fails at the ReplaceAll step. There is no reason for ReplaceAll to fail on form load but work on blur events. My FormatCurrency function also fails if I try to run it on form load.
THIS ALSO FAILS @ i = i.replaceAll(',', '');
$(document).ready(function () { var i = ''; i = $('.string input').val(); i = i.replaceAll(',', ''); $('.string input').val(i); String.prototype.replaceAll = function(str1, str2, ignore) { return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2); } });
Update:
Just determined that adding a half-second delay before running any java and everything works on load. Isn't that the reason for the Document Ready function though? I know I could run java code instantly on load up until now.