function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ap30Ap30 

JavaScript in visualforce not working

Hello All,
Below code is not workinng. I'm not getting alert message when name is not entered.I tried all possible ways. 
====================
<apex:page controller="vendorRegistration" id="page">

<script>
    function getValidation()
    {
     alert('hi');
    
     var n = document.getElementById('{!$Component.page.form.pb.pbs.name}');
       if(n.value =="")
       {
            alert("Name is mandatory");
       }
       

    }
</script>

  <apex:form id="form">
  
  <apex:pageBlock title="Registration Form" id="pb">
  <apex:pageBlockSection columns="2" id="pbs">
  Company Name :<apex:inputText value="{!vcname}" id="name"/>
    </apex:pageBlockSection>
  <apex:outputPanel >
  <apex:commandButton value="Send Email" id="email" action="{!sendEmail}" onclick="getValidation();"/>
  
  </apex:outputPanel>
  
  
  </apex:pageBlock>
  
  </apex:form>
</apex:page>
Best Answer chosen by Ap30
Maharajan CMaharajan C
Hi,

I have tried your same code. Am also facing the same issue. Then i debug it and found due to your second alert the JS is not working. The below alert line causing the issue.
if(n.value == "")
       {
            alert("Name is mandatory");
       }

But am not able to see any issue on the above alert line . So i have removed the above alert line and typed again it started working. So just copy and use the below code.
 
<script>
    function getValidation(){
        alert('hi');
        var n = document.getElementById('{!$Component.page.form.pb.pbs.name}');
        alert(' n-> ' + n );
        
        if(n.value == "")
        {
            alert("Name is mandatory");
        }
    }
</script>

XXX ======================== XXX

one more suggestion i have for you. Use the Action function to call the Apex class Send Email action after JS Validation.

 
<apex:page controller="vendorRegistration" id="page">

<script>
    function getValidation(){
        alert('hi');
        var n = document.getElementById('{!$Component.page.form.pb.pbs.name}');
        alert(' n-> ' + n );
        
        if(n.value == "")
        {
            alert("Name is mandatory");
        }
		else{
            sendEmail();
        }
    }
</script>

  <apex:form id="form">
  
  <apex:actionFunction action="{!sendEmail}" name="sendEmail" rerender="pb"/>

  
  <apex:pageBlock title="Registration Form" id="pb">
  <apex:pageBlockSection columns="2" id="pbs">
  Company Name :<apex:inputText value="{!vcname}" id="name"/>
    </apex:pageBlockSection>
  <apex:outputPanel >
  <apex:commandButton value="Send Email" id="email" onclick="getValidation();;return false;"/>
  
  </apex:outputPanel>
  
  
  </apex:pageBlock>
  
  </apex:form>
</apex:page>


Thanks,
Maharajan.C