I am trying to use the static resource "dateformat" a javascript file containing the following code to auto-format the input of an apex input text field.
When I embed the script directly into the VFP with <script>
tags it works, but when I try to include it as a static resource <apex:includeScript value="{!$Resource.dateformat}"/>
it does not.
Why?
var date = document.getElementById('page1:form1:searchBlock:searchSection:j_id6:DOB');
console.log('date: ' + date);
function checkValue(str, max) {
if (str.charAt(0) !== '0' || str == '00') {
var num = parseInt(str);
if (isNaN(num) || num <= 0 || num > max) num = 1;
str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString();
};
return str;
};
date.addEventListener('input', function(e) {
this.type = 'text';
var input = this.value;
if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3);
var values = input.split('/').map(function(v) {
return v.replace(/\D/g, '')
});
if (values[0]) values[0] = checkValue(values[0], 12);
if (values[1]) values[1] = checkValue(values[1], 31);
var output = values.map(function(v, i) {
return v.length == 2 && i < 2 ? v + '/' : v;
});
this.value = output.join('').substr(0, 14);
});
date.addEventListener('blur', function(e) {
this.type = 'text';
var input = this.value;
var values = input.split('/').map(function(v, i) {
return v.replace(/\D/g, '')
});
var output = '';
if (values.length == 3) {
var year = values[2].length !== 4 ? parseInt(values[2]) + 2000 : parseInt(values[2]);
var month = parseInt(values[0]) - 1;
var day = parseInt(values[1]);
var d = new Date(year, month, day);
if (!isNaN(d)) {
document.getElementById('result').innerText = d.toString();
var dates = [d.getMonth() + 1, d.getDate(), d.getFullYear()];
output = dates.map(function(v) {
v = v.toString();
return v.length == 1 ? '0' + v : v;
}).join(' / ');
};
};
this.value = output;
});
EDIT:
I also tried adding IDs to each apex element and getting the elementId of the inputText that way: {!$Component.page.form.pgBlk.pgBlkSec.pgBlkSecItem.txtName}
, but the date var is still null.
<apex:page id="page">
<apex:form id="form">
<apex:pageBlock id="pgBlk">
<apex:pageBlockSection id="pgBlkSec">
<apex:pageBlockSectionItem id="pgBlkSecItem">
<apex:inputText id="txtName" />
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
window.onload=
even work?