How to refer VisualForce Elements from jQuery / JavaScript
Normally we use JavaScript with webpages. When we build VisualForce pages, there also we use JavaScript to add functionality. But the way we should refer VisualForce elements from JavaScript is little different. Normally people faces problem while locating the VisualForce elements from JavaScript and sometimes the way people refer VisualForce elements from JavaScript is not the best way to do (which definitely leads to many other problems/issues in future). So in this post, I will go one by one so that we can understand the problem and then we will identify the solutions to overcome that problem. At the end of this post, we will know the best practice. Sounds great, right!!!I am super excited, so let’s start –Case 1:Normally a VisualForce page will be converted into HTML by Salesforce. During this conversion process, Salesforce uses a hierarchy to build ID values for page elements. Normally we get the reference of an element by ID in JavaScript in document.getElementById(‘ID Name’). But if we follow the same in VisualForce page, it will not work. Let’s see with an example:Let’s consider the below VisualForce page:<apex:page id=”page”> <apex:form id=”form”> What is your name? <p/> <apex:inputText id=”name” onfocus=”myFunc()”/> </apex:form> <apex:includeScript value=”{!URLFOR($Resource.jQuery1_11, ‘/js/jquery-1.11.2.min.js’)}”/> <script> var j$=jQuery.noConflict(); function myFunc(){ var inputTextCatched = document.getElementById(‘name’); inputTextCatched.value = “Sudipta Deb”; } </script></apex:page>In the above example document.getElementById(‘name’);will not work and will return no result. The reason behind is that...
Read More