[SalesForce] jQuery in VisualForce is not working

I know this is very basic!

I am learning to implement jQuery in VisualForce page development. As part of that I have tried the following code (just playing around). The purpose of the code is: If I click on the button, the input text field should populate with the text which is not happening. Please let me know if there is anything wrong in this.

<apex:page standardController="Account">
<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" />
<script>
    $(document).ready(function(){
        $("#button").click(function(){
            $(#sampleText).val('This is Sample Text');
        });
    });
</script>
<apex:form >
<apex:pageBlock title="Testing jquery">
<apex:inputText id="sampleText" /> 
<apex:commandButton id="button" value="Save"/>
</apex:pageBlock>
</apex:form></apex:page>

Best Answer

You should read these articles:

You do not need to use an "ends with" selector to get your script working. The approach recommended by Salesforce is to use the $Component global variable, and this works just fine:

<apex:page id="thePage">
    <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" />
    <script>
    (function (D, $) {
        "use strict";
        $(function(){
            var literalButtonId = "{!$Component.thePage.theForm.theBlock.button}",
                literalInputId = "{!$Component.thePage.theForm.theBlock.sampleText}",
                button = D.getElementById(literalButtonId),
                input = D.getElementById(literalInputId);
            $(button).click(function(event) {
                event.preventDefault();
                $(input).val('This is Sample Text');
            });
        });
    }(document, jQuery.noConflict()));
    </script>
    <apex:form id="theForm">
        <apex:pageBlock title="Testing jquery" id="theBlock">
            <apex:inputText id="sampleText" /> 
            <apex:commandButton id="button" value="Save" />
        </apex:pageBlock>
    </apex:form>
</apex:page>

Personally, however, I prefer class selectors, which feel like less of an abuse of the system:

<apex:page>
    <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" />
    <script>
    (function ($) {
        "use strict";
        $(function(){
            $(".sampleButton").click(function() {
                $(".sampleInput").val('This is Sample Text');
            });
        });
    }(jQuery.noConflict()));
    </script>
    <apex:form>
        <apex:pageBlock title="Testing jquery">
            <apex:inputText styleClass="sampleInput" /> 
            <apex:commandButton styleClass="sampleButton" value="Save" />
        </apex:pageBlock>
    </apex:form>
</apex:page>
Related Topic