So I noticed that a piece of Javascript on my VisualForce page was working in some cases, and wasn’t in others. JS was doing some operations on a textArea field from one of the custom objects we have. I realized that JS was breaking whenever that textArea field had a new line or carriage return character in it (\n and \r).
So I ended up using a replaceAll() method in the page controller, and removing all of those characters from that textArea field on page load. By the time it got to JS, it was a legal string.
on the VF PAGE:
<script language="JavaScript">
function someFunction() {
var leftOver = 220;
if('{!shippingAddress.Delivery_Requirements__c}'.length > 0){
leftOver -= '{!shippingAddress.Delivery_Requirements__c}'.length;
}
}
</script>
in the controller:
//a fix for the text area field - '\n' and '\r' breaks JS on the VF page
shippingAddress.Delivery_Requirements__c = shippingAddress.Delivery_Requirements__c.replaceAll('\r\n', ' ');
Posting this as a heads up for anyone who encounters JS working for some records and not for others.
If you have insight on why it breaks, do tell.
It’s breaking because JavaScript doesn’t allow literal line breaks in strings. This would probably fix it while allowing the line breaks:
Then in the VF page, bind to the getter from above:
Update:
manubkk’s answer is better. But I think the correct javascript syntax would be: