[SalesForce] Hide/Show Text Field Based upon Radio Button

I have 3 radio buttons in my visaulforce page, and 2 text fields. When I click the first radio button, at that time the first text field should be displayed. When I click the second radio button, the second field should be displayed. When I click the third radio button, again, the second field should be displayed. I am using javascript to hide/show the text fields but it's not working. Can anyone please give me a suggestion?

<script type="text/javascript">

function show(t)
{
    if ( t.value == 0 ){
        document.getElementById("defaultcost").style.display = 'block';
        document.getElementById("differcost").style.display = 'none';
    }
    else{
      document.getElementById("defaultcost").style.display = 'none';
      document.getElementById("differcost").style.display = 'block';
    }     
}
</script>

VF Page

<apex:pageBlockSection>
    <apex:selectRadio value="{!Quote__c.shipping_type__c}" onChange="show(this);">
        <apex:selectOption itemLabel="Use Store Settings" itemValue="0" />
        <apex:selectOption itemLabel="Per Item" itemValue="1" />
        <apex:selectOption itemLabel="Fixed Price Per Order" itemValue="2" />   
    </apex:selectRadio>

    <apex:inputField value="{!Quote__c.storeprice__c}" id="defaultcost" style="display:block;"/><br/>
    <apex:inputField value="{!Quote__c.price__c}" id="differcost" style="display:none;"/><br/>         
</apex:pageBlockSection>

Best Answer

I think that you have there 2 errors in javascript:

  1. You can't access a select.value element directly in javascript (only by using jquery or other framework). So you should change the t.value and get selected value using other code. google knows
  2. You can't reference directly in javascript using getElementById a field input id that has been set in visualfore (defaultcost), that is because SF create the input html element adding a "special" id. for instance: id_j7.ju77_3.defaultcost

My suggestion is to include jquery in your page an replace your javascript show method by this:

function show(t)
{
    if ( $(t).val() == 0 ){

        $('[id$="defaultcost"]').show();
        $('[id$="differcost"]').hide();
    }
    else{
       $('[id$="defaultcost"]').hide();
       $('[id$="differcost"]').show();

    }     
}