0

Can someone help us? Why javascript alert didn't show? Please see my code below. (bold)

<apex:page controller="CreatingNewProfileCtrl" sidebar="false" tabStyle="Notification__c" id="page">

**<script>

    function validateValue(){

    var cname = document.getElementById('{!$Component.page:mainForm:pePageBlock:pePageBlockSection:wtable:cn}').value;
        if(cname == "") {

            alert('company name is null');               

            return false;

        } else {
            alert('company name is not null');

        }

    }

</script>**


<div style="padding: 10px 25px 0px 25px;">    

    <apex:form id="mainForm">   
    <br/>

    <div class="tab-content" id="tabs">

        <div class="tab-pane" id="home1">
        <apex:pageMessages />
            <apex:outputPanel id="peTab">
                <div> <br/>


                    <div style="float:right;">                   
                        **<apex:commandButton value="test button" onComplete="validateValue();" />**

                    </div>
                </div>

                <apex:pageBlock mode="edit"  id="pePageBlock">
                    <apex:pageBlockSection title=""   id="pePageBlockSection"/>

                    <apex:outputPanel id="myPanelPE">
                        <apex:pageBlockTable value="{!proExpWrappers}" var="profExpWrap" id="wtable">                                                           

                            <apex:column headerValue="Company Name" id="companyName">
                                <apex:outputPanel styleClass="requiredInput" layout="block">
                                    <apex:outputPanel styleClass="requiredBlock" layout="block"/>
                                        **<apex:inputField value="{!profExpWrap.profExp.Name}" id="cn" required="{!cName}" />**                                    
                                </apex:outputPanel> 
                            </apex:column>

                        </apex:pageBlockTable>
                        <br/>         

                    </apex:outputPanel>

                </apex:pageBlock>

            </apex:outputPanel>                

        </div>

    </div>
</div>

</apex:page>

Here's my controller

public class CreatingNewProfileCtrl {

public Contact c;
public Professional_Experience__c professionalExperience     {get;set;}

public String sec_Quest {get;set;}

// List for notification
public List<Notification__c> notifcurrList                      {get;set;}
public List<Notification__c> allNotif                           {get;set;}

// List for Professional Experience
public List<ProfExpWrapper> proExpWrappers                      {get;set;}
public List<Professional_Experience__c> deletePEList            {get;set;}
public List<Professional_Experience__c> profExpListtoInsert     {get;set;}

// professional experience
public Professional_Experience__c professionalExp {get;set;}
public static Integer toDelIdent                  {get;set;}
public static Integer addCount_pe                 {get;set;} 


 // professional experience
private Integer pe_nextIdent = 1;

Boolean pageRefresh = false;
public static final string PAGE_CREATE_NEW_PROFILE = '/apex/CreatingNewProfile';


public Contact getc(){
    if (c == null){ 
        c = new Contact();
    }
    return c;
}

// CONSTRUCTOR
public CreatingNewProfileCtrl() {

    notifcurrList = [SELECT Id, CreatedDate, Message__c FROM Notification__c WHERE CreatedDate = THIS_WEEK ORDER BY CreatedDate DESC];
    notifcurrList.size();
    allNotif = notifcurrList;

    // Professional Experience (Initial Row)
    proExpWrappers = new List<ProfExpWrapper>();
    for (Integer idx=0; idx<3; idx++){
        proExpWrappers.add(new ProfExpWrapper(pe_nextIdent++));
    } 
    deletePEList  = new List<Professional_Experience__c>();      

}


//--------------------------------------------- PROFESSIONAL EXPERIENCE ------------------------------------------------//

public class ProfExpWrapper{
    public Professional_Experience__c profExp {get;set;}
    public Integer ident {get;set;}
    public ProfExpWrapper(Integer pe_inIdent){
        ident = pe_inIdent;
        profExp = new Professional_Experience__c();
    }      
}

public void delWrapperPE(){ 

    Integer toDelPos =- 1;
    deletePEList = new List<Professional_Experience__c>();

    for (Integer idx=0; idx<proExpWrappers.size(); idx++){
        if (proExpWrappers[idx].ident==toDelIdent){
            toDelPos=idx;
        }
    }

    if (-1!=toDelPos){
        if(proExpWrappers.size() !=1){            
            deletePEList.add(proExpWrappers[toDelPos].profexp);
            proExpWrappers.remove(toDelPos);
        }else{
            proExpWrappers.remove(toDelPos);
        }       
    }

}

public void CreateProfExp() {

    profExpListtoInsert = new List<Professional_Experience__c>();
    profExpListtoInsert.clear();       

    for (ProfExpWrapper pew : proExpWrappers) {

        if ( !String.isBlank(pew.profExp.Name) ) { //&& !String.isBlank(pew.profExp.Job_Title__c) &&  !String.isBlank(pew.profExp.Job_Description__c) ) {

            professionalExperience = new Professional_Experience__c();

            professionalExperience.Name                 =     pew.profExp.Name                 != null ? pew.profExp.Name : '';
            professionalExperience.White_Label__c       =     pew.profExp.White_Label__c       != null ? pew.profExp.White_Label__c : '';
            professionalExperience.Job_Title__c         =     pew.profExp.Job_Title__c         != null ? pew.profExp.Job_Title__c : '';
            professionalExperience.Start_Date__c        =     pew.profExp.Start_Date__c;       // != null ? pew.profExp.Start_Date__c : '';
            professionalExperience.End_Date__c          =     pew.profExp.End_Date__c;         // != null ? pew.profExp.End_Date__c : '';
            professionalExperience.Job_Description__c   =     pew.profExp.Job_Description__c   != null ? pew.profExp.Job_Description__c : ''; 

            //if (!String.isBlank(pew.profExp.Name) && !String.isBlank(pew.profExp.Job_Title__c) && !String.isBlank(pew.profExp.Job_Description__c) && pew.profExp.Start_Date__c != null ) {
                profExpListtoInsert.add(professionalExperience);                    
           // }                                

        }                                 

    }

}


public void matchToContactID(Contact cont) {
    // Professional Experience        
    if(profExpListtoInsert != null){
        for(Professional_Experience__c pe: profExpListtoInsert){
            pe.Employee_ID__c = cont.Id;           
        }
        insert profExpListtoInsert;
    }


}


// -------------------------------------------- SAVING PROFILE --------------------------------------------------- //
public PageReference CreateNow() {

PageReference pageRef;

    try {

    CreateProfExp();

        if ( !String.isBlank(proExpWrappers.get(0).profExp.Name)
        && String.isBlank(proExpWrappers.get(0).profExp.Job_Title__c) ) {
            //ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Please enter Job title')); 


        if ( !String.isBlank(proExpWrappers.get(0).profExp.Name)
        && String.isBlank(proExpWrappers.get(0).profExp.Job_Description__c) ) {
            //ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Please enter Job Description')); 

        } 

        if ( !String.isBlank(proExpWrappers.get(0).profExp.Name)

        && proExpWrappers.get(0).profExp.Start_Date__c == null ) {

        }                   

        if ((!String.isBlank(proExpWrappers.get(0).profExp.Name)) 
        && (!String.isBlank(proExpWrappers.get(0).profExp.Job_Title__c) 
        &&  !String.isBlank(proExpWrappers.get(0).profExp.Job_Description__c) 
        && proExpWrappers.get(0).profExp.Start_Date__c != null ) ) {

            CreateProfExp();

        }

            customSecQuest();
            c.AccountId = '0012800001B2ofk'; 
            insert c;  // saving contact record
            matchToContactID(c);
            pageRef = new PageReference('/'+c.Id); 
            pageRef.setRedirect(true);

    } catch(Exception e){
        ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR, e.getMessage());
        ApexPages.addMessage(myMsg);
        //clearLists(); 
    }

    pageRefresh = true;
    return pageRef;

}    






}
7
  • can you try minimizing your code? you should also add your controller. Please take some time to read How to Ask for improving the quality of your questions. Thanks
    – glls
    Commented May 8, 2017 at 3:02
  • Hi @glls. I removed all the unnecessary tags on my VF page. I think controller is not needed. We just want to check the inputField if it has a value or null as well as the Javascript alert.
    – lone
    Commented May 8, 2017 at 3:15
  • what is your cname variable returning?
    – glls
    Commented May 8, 2017 at 3:17
  • cname should be the value of the inputField. if the inputField has a value it should shown an alert('Company Name is not null'); and if it is null alert(Company Name is null);
    – lone
    Commented May 8, 2017 at 3:21
  • that is not what I am asking, what is cname returning right now? have you tried debugging your code?
    – glls
    Commented May 8, 2017 at 3:21

1 Answer 1

1

To retrieve the attribute value instead of using ':' you have to use dot and specify entire DOM hierarchy.

document.getElementById('{!$Component.page.mainForm.pePageBlock.pePageBlockSection.myPanelPE.wtable.companyName.anOutputPanel.cn}').value;

You would also need to add an id to the output panel containing the inputField to reference it through the component global variable:

<apex:outputPanel styleClass="requiredInput" layout="block" id="anOutputPanel">
    <apex:inputField value="{!profExpWrap.profExp.Name}" id="cn" required="{!cName}" />

Other ways you can achieve the value using tag name getElementsByTagName like this which will help to validate multiple inputs:

<script type="text/javascript">
function buttonValidate(){
    alert('inside buttonValidate');
    //identify the table 
    var table = document.getElementById('{!$Component.mainForm.pePageBlock.pePageBlockSection.wtable}');
    //retrieve the row count
    var rowCount = table.rows.length;
    //loop through the table rows    

    for(var i=0; i < rowCount; i++) {        
        var cells = table.rows[i].getElementsByTagName('input');
        alert('cells=' + cells); 
        //eliminate header row
        if(cells.length>0){
            //print the inputField value
            alert(cells[0].value);
        }
    }
}
</script>

Or, by using getElementsByClassName

<apex:inputField value="{!profExpWrap.profExp.Name}" id="cn" styleClass="myElement"/>

<script type="text/javascript">
function buttonValidateUsingStyleClass(){
    alert('inside buttonValidateUsingStyleClass');
    //identify the table 
    var table = document.getElementById('{!$Component.mainForm.pePageBlock.pePageBlockSection.wtable}');
    var elements = table.getElementsByClassName('myElement');
    alert(elements);

    for(var i=0; i<elements.length; i++)
    {
        //it will display inputField value
        alert(elements[i].value);
    }
}

</script>

Update based on comments

You have to use oncomplete, Mind the lower case. Refer documentation

<apex:commandButton value="test button" oncomplete="validateValue();" />
6
  • Hi @Santanu, thanks for your response. We've tried using 'dot' insted of ':' and still it's not working. We also try the getElementbyTagName and ClassName that you've provided and both are not working.
    – lone
    Commented May 8, 2017 at 4:38
  • post your controller code also how you are assigning Commented May 8, 2017 at 4:38
  • Next time, please post complete code samples as requested in the first comment under your question. This is to avoid back and forth and not waste other peoples time. Please take some time to review How to Ask if you have not done so already. Remember, we are all here to help, so help us help you!
    – glls
    Commented May 8, 2017 at 4:54
  • I have updated my answer. you need to use oncomplete like this. Also remove unnecessary code from the question Commented May 8, 2017 at 4:58
  • Santanu, the above comment was intended for @lone . =P
    – glls
    Commented May 8, 2017 at 5:15

You must log in to answer this question.

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