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>
Best Answer
I believe you can achieve it by
required
attribute alone ininputText
instead of using Javascript. You have to include:<apex:pageMessages/>
in you VF page to show any errors.