[SalesForce] Calling Javascript function from InputField

Below is how I am calling JS function from inputField :

<apex:inputField id="InputFieldId" onclick="restrictCurrencyValue('{!$Component.pageBlockId.PageBlockSectionItemId.InputFieldId}')" value="{!TelecomMap[key].Amount__c}" />

Below is my JS :

function restrictCurrencyValue() {
    alert("Function called");
        var amountValue = document.getElementById("{!$Component.pageBlockId.PageBlockSectionItemId.InputFieldId}");
        var enteredAmount = amountValue;
        if(enteredAmount == '')
        return false;
        var regExp = /^(?!\.?$)\d{0,6}(\.\d{0,2})?$/; //Declare Regex
        var amountVal = enteredAmount.match(regExp); 
        if (amountVal == null){
            alert("Error");
        }
}

Please let me know if that is the current format of calling JS.
Also any help on JS is also appreciated since I am complete rookie in that.

Best Answer

Correct way of doing this as follows. {!$Component.InputFieldId} will consider entire DOM hierarchy, since you are passing that as a parameter of onclick event of that field.

Also, that approach is specially helpful when you are displaying records dynamically and building a table. So there will be array of components. Now if you do not pass as a parameter to javascript function then you need to loop through the array and find out the field value.

If you do not pass fieldId as parameter and if you try to access that inputField from Javascript function then you have to specify entire DOM hierarchy explicitly.

<apex:inputField id="InputFieldId" 
    onclick="restrictCurrencyValue('{!$Component.InputFieldId}')" 
    value="{!TelecomMap[key].Amount__c}" />

Javascript

function restrictCurrencyValue(fieldId) {
    alert("Function called");
        var amountValue = document.getElementById(fieldId).value;
        var enteredAmount = amountValue;

}

Also it will work

<apex:inputField id="InputFieldId" 
    onclick="restrictCurrencyValue()" 
    value="{!TelecomMap[key].Amount__c}" />

Javascript

function restrictCurrencyValue() {
    alert("Function called");
        var amountValue = document.getElementById("{!$Component.pageBlockId.PageBlockSectionItemId.InputFieldId}").value;
        var enteredAmount = amountValue;
}