4

How can I get the force.com generated id from the $Component global varible for me apex:selectRadio component?

Javascript

var rdo = j("input[@id=" + jq('{!$Component.searchRdo}') + "]:checked").val();

Visualforce Page

<apex:composition template="FindYourPlaceSiteTemplate">
        <apex:define name="body">

            <apex:form id="form">
                <apex:pageMessages />
                <div class="tabs">        
                    <ul>
                        <li><a href="#campusMinistry">{!$Label.FYPTabCollegiateMin}</a></li>
                        <li><a href="#schoolSCU">{!$Label.FYPTabUMSchools}</a></li>
                        <li><a href="#schoolWMC">{!$Label.FYPTabWorldMethodist}</a></li>
                    </ul>

                    <div id="campusMinistry">
                        <table>
                            <tr>
                                <td valign="top"><label for="institution_autocomplete">{!$Label.FYPSearch}: </label></td>
                                <td>
                                    <input id="institution_autocomplete" maxlength="50" size="50" />
                                    <apex:selectRadio value="{!searchOption}">
                                        <apex:selectOptions id="searchRdo" value="{!searchOptions}"/>
                                    </apex:selectRadio>
                                    <p style="font-size: small">{!$Label.FYPSearchByInst}</p>
                                </td>
                            </tr>
                        </table>

My page source always ends up looking like this:

var rdo = j("input[@id=" + jq('') + "]:checked").val();
1

5 Answers 5

5

UPDATE: Read this blog spot, maybe it can help you: Element ID in JQuery – Visualforce problem


The point here is, that the component must be rendered at time you are reading these id.

Example: here we are reading the id of component that was rendered before the javascript. And it work.

<apex:outputText value="myText" id="textField" />

<script>
    var id = '{!$Component.textField}';
</script>

Next example will not work, because the component does not exist at the time of reading the id.

<script>
    var id = '{!$Component.textField}';
</script>

<apex:outputText value="myText" id="textField" />

I recommend jQuery for reading id's:

<apex:outputText value="myText" id="textField" />

jQuery('[id$=textField]').hide();

Here we take the DOM object with id that ends with 'textField'.

3
  • Why wouldn't $Component.searchRdo have the id at that point? It's being generated and then rendered. The issue seems to be that I'm not grabbing the component the right way, as in maybe my path is wrong: $Component.form.someid.searchRdo or something. Maybe I'm wroing.
    – fourq
    Commented Dec 11, 2012 at 19:29
  • At your code example i can see, that var rdo attempts to access the component searchRdo that is rendered later on the page., so var rdo gets a null. Could you post complete code of you page? Commented Dec 11, 2012 at 19:41
  • Grabbing the id after the component rendered did it. I then was able to get what I needed by using var searchOpt = j("input[@id=" + searchRdo + "]:checked").val(); where searchRdo is the $Component.searchRdo value. Thanks
    – fourq
    Commented Dec 11, 2012 at 21:40
2

Since it looks like you are already using jQuery, try partial selectors: http://api.jquery.com/attribute-starts-with-selector/

4
  • My issue is that $Component.searchRdo is not returning an id.
    – fourq
    Commented Dec 11, 2012 at 18:49
  • Sorry, my answer was way too brief. Drive by commenting. I think you'll be better served by putting the id on apex:selectRadio (not the options)and then using jQuery to determine the val() from there. For jQuery integration, I don't really rely on $Component, for reasons like this - but even when it generates the ID it will probably not survive rerenders, etc., and the formatting is somewhat CSS unfriendly as well. However, I think val() from the options object get the value you're looking for, and the partial selector should then responds to "searchRdo"- at least that should be in the id.
    – joshbirk
    Commented Dec 11, 2012 at 19:11
  • ahh, that's too bad really. I was hoping that my js func for escaping semi-colons and periods used together with $Component were going to well. Thanks.
    – fourq
    Commented Dec 11, 2012 at 19:24
  • add the id to the selectRadio just adds an id to the surrounding table: <table id="searchRdo" I think @mast0r might be on to something but I'm not sure I understand why right now. Why would the $Component var not have the id at that time? I mean force.com generates it.
    – fourq
    Commented Dec 11, 2012 at 19:26
2

I was able to get the component id to render properly by making the request within the same context of Visualforce code.

For example, I have had success by assigning the id to a variable immediately in JavaScript:

<apex:selectRadio value="{!searchOption}">
  <apex:selectOptions id="searchRdo" value="{!searchOptions}"/>
</apex:selectRadio>
<script>
  var searchId = '{!$Component.searchRdo}';
<script>
1
  • Yes this worked and then I was able to get the radio option by doing this: var searchOpt = j("input[@id=" + searchId + "]:checked").val();
    – fourq
    Commented Dec 11, 2012 at 21:39
1

You could try using an increment + listener:

HTML

<li class="item" data-number="' + (gmarkers.length - 1) + '">

HTML Source

<div class="panel-search-result" data-panel="search-result" style="height: 564px;">
<h1 class="head">Search Results</h1>
<div data-placeholder="result">
    <ul class="search-result-list">
        <li class="item" data-number="0">
            <h2 class="name">ALLERGY TESTING CENTER</h2>
            <div class="address">30 NEWBRIDGE RD<br>EAST MEADOW NY, 11554</div>
            <div class="phone">5167315740</div>
        </li>
    </ul>
</div>
</div>

JQ/JS

var $searchResult = $("[data-panel='search-result']");

$searchResult.on({
  click: function(event) {
        var i = $(this).data('number');
        incrementZIndex();
        gmarkers[i].setZIndex(incrementZIndex.counter);
        infoBox.setContent(gmarkers[i].desc);
        infoBox.open(map, gmarkers[i]);
  }
}, "li");
1
  • but what about when I use apex:selectRadio ?
    – fourq
    Commented Dec 11, 2012 at 19:05
0

Your ID should be defined on the apex:selectRadio tag so that the option elements all have the same element name value, not defined on the apex:selectOptions tag. You will be using the name attribute to find the selected element in the named group.

The $Component reference knows only about its ancestors and siblings within the VisualForce hierarchy. Using the $Component reference outside of VF any tags, in a head script block for instance, requires you to define the full hierarchy path to the element which you are targeting.

Because your question contains a partial VF page, you may need to experiment with this a bit to get the path hierarchy correct in your specific scenario but I assure you it does work. Since your apex:selectRadio 'searchRdo' element is defined within the apex:form tag with an ID of 'form', the full path to the component will look something like this:

(please note that I also modified the original jQuery selector to use the name attribute to find the checked element in the option collection)

var rdo = j("input[name=" + jq('{!$Component.form.searchRdo}') + "]:checked").val();

See this SalesForce Best Practices page for more information about the ancestor and sibling references in the component hierarchy: Best Practices for Accessing Component IDs

Here is a trivial example:

<apex:page controller="YourControllerName">
    <script>
    var optionsGroupName = '{!$Component.theForm.searchRdo}';

    // after jQuery is loaded and page is rendered
    // console.log(jQuery('[name="' + optionsGroupName + '"]:checked'));

    </script>
    <apex:form id="theForm">
        <apex:selectRadio value="{!selectedOption}" id="searchRdo">
            <apex:selectOptions value="{!availableOptions}" />
        </apex:selectRadio>
    </apex:form>    
</apex:page>

Hope this helps!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .