Explore Courses Blog Tutorials Interview Questions
0 votes
in Salesforce by (11.9k points)

I have apex tag that generates input text field.

<apex:page id="my_page">

    <apex:inputText id="foo" id="c_txt"></apex:inputText>


When someone clicks this field, I want to execute javascript.

But when I check the HTML source, this apex tag which becomes input tag has (I think) dynamically generated part.

  <input type="text" size="50" value="Tue Nov 16 00:00:00 GMT 2010" 

name="j_id0:j_id3:j_id4:c_txt" id="j_id0:j_id3:j_id4:c_txt">

As you can see id has junk part :(


In my Javascript, I'm trying to getElementById('c_txt') but this does not work of course. How to deal with this???


Seems like I can do this but not working...

<apex:includeScript value="{!URLFOR($Resource.datepickerjs)}"></apex:includeScript>

<apex:inputText id="foo" id="c_txt" onclick="javascript:displayDatePicker()" />


var elem = getElementById('c_txt');


The alert shows 'null' so something must be wrong.

Even this alert returns null...

var targetDateField = document.getElementById('{!$Component.my_page:c_txt}');


1 Answer

0 votes
by (32.1k points)
edited by

 Hey! You have used $Compoent global visualforce expression. It can only be used in visualforce code, but not inside of Javascript.

The code below works precisely. It actually outputs the value in the inputText field to js alert message. Now you can pass the ID attribute to the Javascript and process whatever the task is needed.

Created Date: <apex:inputText id="dah" value="{!created}" size="50" 



  function go(field) {

    var huh = document.getElementById(field).value;

    alert(huh); //returns the string u put inside of input text field



 Enroll in our Best Salesforce Course to get a professional certification!

Browse Categories