I am trying to use javascript to make a field required/not required. The scenario is to make Employees on Account as required when Account type is Other. When the Account type is selected as press, With the help of javascript i could make the red bar disappear, but the validation Error : You must enter a value is still thrown when I click on save.
Can someone help me identify what I am missing?
<apex:page standardController="Account" tabStyle="Account" showHeader="true" sidebar="true">
<style>
.requiredBlock {
background-color: #C00;
position: absolute;
left: -4px;
width: 3px;
top: 1px;
bottom: 1px;
}
.notrequiredBlock {
background-color: red;
position: absolute;
left: -4px;
width: 3px;
top: 1px;
bottom: 1px;
}
</style>
<script language="javascript" type="text/javascript">
window.onload = function() {
$(".coverPrct")[0].parentElement.children[0].className = '';
}
function makeReq(){
console.log($(".coverPrct")[0]);
if($(".coverPrct")[0].parentElement != null){
$(".coverPrct")[0].parentElement.children[0].className = '';
}
//console.log($(".pastPracticeCoverageId")[0].value +'Coverage' );
if($(".pastPracticeCoverageId")[0].value != null && ($(".pastPracticeCoverageId")[0].value == 'Other')){
//alert('Passed');
console.log('Before ' + $(".coverPrct")[0].parentElement.children[0].className);
$(".coverPrct")[0].parentElement.children[0].className = 'requiredBlock';
}
else{
$(".coverPrct")[0].parentElement.children[0].className = '';
}
}
</script>
<apex:pageBlock title="Test">
<apex:pageBlockButtons >
<apex:commandButton value="save" title="Save"/>
<apex:commandButton value="cancel" title="Cancel"/>
</apex:pageBlockButtons>
<apex:pageBlockSection >
<apex:inputField value="{!Account.Name}" required="true"/>
<apex:inputField onchange="makeReq()" styleClass="pastPracticeCoverageId" value="{!Account.Type}"/>
<div id="coverageField">
<script language="javascript" type="text/javascript">
console.log($(".coverPrct")[0]);
if($(".coverPrct")[0].parentElement != null){
$(".coverPrct")[0].parentElement.children[0].className = '';
//$(".coverPrct")[0].value = 0;
}
//console.log($(".pastPracticeCoverageId")[0].value +'Coverage' );
if($(".pastPracticeCoverageId")[0].value != null && (($(".pastPracticeCoverageId")[0].value == 'Other') )){
//alert('Passed');
console.log('Before ' + $(".coverPrct")[0].parentElement.children[0].className);
$(".coverPrct")[0].parentElement.children[0].className = 'requiredBlock';
//$(".coverPrct")[0].parentElement.innerHTML = "<div class='requiredInput'>"+ $(".coverPrct")[0].parentElement.innerHTML + "</div>";
}
else{
$(".coverPrct")[0].parentElement.children[0].className = '';
//$(".coverPrct")[0].value = 0;
}
</script>
<apex:inputField styleClass="coverPrct" value="{!Account.NumberOfEmployees}" required="true" >
<div class="requiredBlock"></div>
</apex:inputField>
</div>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>