[SalesForce] I wanna make input text field required using javascript ,but currently its not working as expected,though it works as expected for checkbox field

I am not able to detect what I am doing wrong in this piece of code

<apex:page >
<apex:form id="myForm">
    <apex:pageblock id="pb1">
        <apex:pageblockSection id="pbs1">
            <apex:inputText id="Name" label="Enter Name" required="true"/>
            <apex:inputCheckbox id="checkbox1" label="Check Me" />
            <apex:commandButton value="Click Me !" onclick="getCheckBoxValue();"/>
        </apex:pageblockSection>
    </apex:pageblock>
</apex:form>
<script language="javascript">
    function getCheckBoxValue()
    {

       if(document.getElementById('{!$Component.myForm.pb1.pbs1.Name}').value == '')
        {
            alert('Name is mandatory');
        }

       else
       {
           alert('You have entered the Name');
       }
    }
</script>

The below code is working fine:

<apex:page >
<apex:form id="myForm">
    <apex:pageblock id="pb1">
        <apex:pageblockSection id="pbs1">
            <apex:inputCheckbox id="checkbox1" label="Check Me" />
            <apex:commandButton value="Click Me !" onclick="getCheckBoxValue();"/>
        </apex:pageblockSection>
    </apex:pageblock>
</apex:form>
<script language="javascript">
    function getCheckBoxValue()
    {
       var status = (document.getElementById('{!$Component.myForm.pb1.pbs1.checkbox1}').checked);
       if(status==true)
       {
           alert('You have checked it.');
       }
       else
       {
           alert('Check it first.');
       }
    }
</script>

Alerts Coming for Checkbox field

Alerts Coming for Checkbox field

Best Answer

I believe you can achieve it by required attribute alone in inputText instead of using Javascript. You have to include:

<apex:pageMessages/>

in you VF page to show any errors.

Error:

<apex:page >
    <apex:pagemessages />
    <apex:form id="myForm">
        <apex:pageblock id="pb1">
            <apex:pageblockSection id="pbs1">
                    <apex:inputText id="Name" label="Enter Name" required="true"/>

                <apex:inputCheckbox id="checkbox1" label="Check Me" />
                <apex:commandButton value="Click Me !" onclick="getCheckBoxValue();"/>
            </apex:pageblockSection>
        </apex:pageblock>
    </apex:form>
    <script>
    function getCheckBoxValue()
    {
        console.log('Getting Val. ');
        if(document.getElementById('{!$Component.myForm.pb1.pbs1.Name}').value == '')
        {
            alert('Name is mandatory');
        }

        else
        {
            alert('You have entered the Name');
        }
    }
    </script>
</apex:page>
Related Topic