Visualforce prefixes the ID that you specify with the ID values of the containing elements. (Use your browser's "View Source" or similar to see this.)
One way to handle this with jQuery is to use jQuery's ends with selector. So instead of:
j$("#id3")
use:
j$("[id$='id3']")
PS
There is also a spurious (
on the line that tests for 'Female'
. Pasting the script into http://jshint.com/ helps find that sort of error (as does looking at your browser's JavaScript console).
PPS
Here is some working code (just using a standard controller and a custom gender field I have in my org:
<apex:page standardController="Contact">
<apex:pageblock>
<apex:form>
<apex:pageblocksection>
<apex:inputField id="gender" value="{!Contact.cve__gender__c}" />
<apex:inputfield id="name" value="{!Contact.Name}" />
</apex:pageblocksection>
</apex:form>
</apex:pageblock>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var j$ = jQuery.noConflict();
j$("document").ready(function() {
var gender = j$("[id$='gender']");
var name = j$("[id$='name']");
function checkGender() {
if (gender.val() == 'Female') {
name.hide();
} else {
name.show();
}
}
gender.on('change', checkGender);
});
</script>
</apex:page>
Further problems were:
- the script tag that includes jQuery needs to be separate from the script tag that contains your local code
- Salesforce defaults the ID values of fields to a patter that ends in values like "id3" and "id4" so the ID values need to be more distinct to avoid matching the wrong element
- more of a code style thing, but repeating the jQuery selectors makes maintenance harder so best to only have them once in the code
- more of a performance thing, but best to render the HTML first and then load the JavaScript so your page appears quicker (i.e. JavaScript at the end)