Change an item Label dynamically

Get it? “an item with many hats”… yeah ok.

Need to change the label of an item on-the-fly? When I run my Apex page it renders item labels like this:

<label for="P1_CONTACT_NUMBER">
  <span>Contact Number</span>
</label>

If the label needs to change based on another item, I could set the label with the value of another item, e.g. “&P1_CONTACT_NUMBER_LABEL.” and when the page is refreshed it would pick up the new label. But at runtime, if the label needs to change dynamically in response to changes in other items, we need to do something else.

Caveat: The need for changing the label should be very rare – it’s bad practice to overload one field with multiple meanings. But if you must, this is what you can do.

It’s easy with a Dynamic Action running some Javascript. This changes the label text for the P1_CONTACT_NUMBER item depending on the value chosen for P1_CONTACT_METHOD, which might be a radio group or select list. The method uses jquery to search for a “label” tag with the attribute “for” that associates it with the desired item; we then navigate down to the “span” element, and call the “text” function to change the label text:

if ($v("P1_CONTACT_METHOD")=='SMS') {
    $("label[for=P1_CONTACT_NUMBER]>span").text("Contact Mobile")
} else if ($v("P1_CONTACT_METHOD")=='EMAIL') {
    $("label[for=P1_CONTACT_NUMBER]>span").text("Contact Email")
} else {
    $("label[for=P1_CONTACT_NUMBER]>span").text("Contact Number")
}

The Dynamic Action is set up as follows:

Event = Change
Selection Type = Item(s)
Item(s) = P1_CONTACT_METHOD
Condition = (no condition)

True Action = Execute JavaScript Code
Fire On Page Load = Yes
Selection Type = (blank)
Code = (the javascript shown above)

Parallel Development in APEX
Build your APEX application better – do less in APEX

Comments

  1. Hi Jeff,

    Thanks for that – I copy pasted some legacy code into a new mobile ( Smartphone UI) app and it didn’t work:
    $(“label[for=’P350_SS_AMOUNT_RAISED’]”).children().html(‘Community Group Profit’);

    However this did – which is based on your code so thanks for that!

    $(“label[for=P350_SS_AMOUNT_RAISED]”).text(“Community Group Profit $ “);

    Not sure why the legacy code didn’t work – certainly works fine on the existing desktop UI.

    • Hi Kevin,

      Yes, it will need to be different depending on the actual HTML that your template is generating. Your mobile UI will usually have very different HTML than your desktop UI.

  2. thank you very much great info

  3. How Can Change an item Label dynamically ( Label from database )?

    • Hi PK,

      That is exactly what this post is about. Is there something that perhaps needs more explanation?

      Jeff

Leave a Reply

Your email address will not be published / Required fields are marked *