Sometimes it is required that we have to access a visual force element in javascript. There are several ways we can do it. As in visual force the id is created by the hierarchy we have to specify the hierarchy to get the element, An alternate solution can be to use a html element instead of a VF element, But in that case we may lose the functionality provided by Salesforce .
Below are the way you can get the element
1) By hard coding the hierarchy , This is not recommended.
Below are the way you can get the element
1) By hard coding the hierarchy , This is not recommended.
<apex:page id="pg">
<apex:pageblock id="pgBlock">
<apex:inputText id="iText"/>
</apex:pageBlock>
<script>
function t(){
document.getElementById("pg:pgBlock:iText");
}
</script>
</apex:Page>
This method is not recommended because inserting new element may break the javascript
2) Using script variable
<apex:page id="pg">
<apex:pageblock id="pgBlock">
<apex:inputText id="iText">
<script>
var elem = '{!$Component.iText}';
</script>
</apex:inputText>
</apex:pageBlock>
<script>
function t(){
document.getElementById(elem);
}
</script>
</apex:Page>
3) Using JQUERY
<apex:page id="pg">
<apex:pageblock id="pgBlock">
<apex:inputText id="iText">
</apex:inputText>
</apex:pageBlock>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js”></script>
<script src=”https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js”></script>
<script>
var j$ = jQuery.noConflict();
j$(document).ready(function() { //your actions };
//To use Visualforce Id’s with jquery there is somewhat different approach as compared to simple HTML element Id’s. You have to use selector as follows:
var compid = j$(“[id $='iText']“);
//Now you can use this variable to perform actions on the elements.like,
compid.hide(); // will hide the element.
</script>
</apex:Page>
No comments:
Post a Comment