0

Anyone help me, why Javascript "getElementById" return null in Visualforce Page.

In my form, I have "Radio button" and "inputtextarea" My requirement is whenever click the radio button in visualforce,based on the condition "inputtextarea" need to hide.Below is my code.

Javascript code:


<script>
    function myFunction(v) 
    {
      var inputcpf = document.getElementById('iptext2');

        // console.log('Id of the Inputtext :' + inputcpf);
        alert(inputcpf);
        if(v.value =="Excellent")
            //document.getElementById("iptext2").style.display="block";
            document.getElementById('iptext2').style.visibility = 'hidden';
        else
            //document.getElementById("iptext2").style.display="none"; 
            document.getElementById('iptext2').style.visibility = 'visible';
            return;            
    }    
    
</script>

Visualforce page Code:


<Table width="100%" border="0" cellpadding="0" cellspacing="0" columns="0" class="big"> 
   <tr >
      <td colspan="5" class="fieldLabel">                     
          <p style="font-size: 20px;">
                 <b> How satisified you are with our Service? </b>
          </p>     

          <apex:selectRadio value="{!SelectedAnswer}"  
                            onclick="myFunction(this)"
                            style="font-size: 20px;font-family:arial;font-weight: bold;" >
                            <apex:SelectOptions value="{!Items}" id="SelOP1"/>                                  
          </apex:selectRadio>
      </td>
    </tr> 
</Table>  
<Table>
     <tr>
       <td>
          <p style="font-size: 15px;">
               <b>How could we improve?</b>
          </p>                               
          <apex:inputTextarea id="iptext2"  value="{!EnteredText}"  style="width: 350px;"/>
        </td>
     </tr>
</Table> 
2

1 Answer 1

1

Visualforce elements (those that start with <apex:) have their id generated from the provided id. You should generally use the $Component variable to access these elements:

document.getElementById("{!$Component.iptext2}")

$Component won't work for components that generate elements in a loop. You'd be better off using something like:

<apex:selectOptions html-data-id="selectOption" ...

So you can then query:

document.querySelectorAll('[data-id="selectOption"]')
1
  • Sorry.. Don't understand. Able to provide sample code. It's a great help for me
    – Tara
    Commented Dec 18, 2022 at 3:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .