How to get values of visualforce components in javascript by id in Salesforce

In visualforce page you can embed and can also write your own javaScript code as we do in HTML pages but to access the values of the visualforce tags is little tricky in salesforce because when visualforce convert to simpler HTML page then salesforce append some code to the ID so it become little tricky to refer those ID in javaScript, let see different method with example code but before moving to the tutorial I just want to clarify that the ID of visualforce tags is different from the salesforce ID , you can see my this post on how to get Salesforce ID in salesforce but in this post the ID of the tags is to identify them so ID is identifier which identify the particular tags in salesforce ,now let’s see how to achieve this.

Getting value in javaScript using $Component

The one method is this that we moved to the ID of that component whose value we want to retrieve by covering each ID of the components starting from the ID of the apex:form tag to that particular component ID , let us see the code and then we would talk about .

so as you can see in the script code that how actually refer the ID of the inputtext field , I have to traverse through all the ID of the components , if you want to refer or to get the value of the particular component then you need to traverse through each ID of the component from the ID of the apex:form to the ID of that particular component you want to retrieve and to make it work you need to call or execute javaScript on particular event as I call the javaScript function on onchange event, you can check the demo from the below link.

Using the above method the pro is that we can refer any component in javaScript using its ID but con is that we need to update our javaScript code each time whenever we move our code from one section to the other section.We can also pass the javascript value to controller or apex class if we need to refer that value in our apex class. There is one more method to refer the component or to get the value of that component for that we need to pass the ID from component to javaScript and then in that javaScript using that ID we can get the value of that component , check below modify code.

The con of this method is that you will only able to pass the ID of that component from the component you are calling javaScript function. You can also take at the demo of the above code from the below link.

I hope you like my this post if you can any query related to this post you can leave a comment below in the comment section i will try to help and don’t forget to subscribe my blog and Facebook pages and you can see more post from the below.