Integrating JavaScript with JSF and Facelets: Handling Hidden Inputs

Hey everyone! I’m working on a project where I need to use JavaScript to change hidden input fields in a JSF/Facelets page. Specifically, I want to set a hidden field to the user’s color depth when the page loads.

I’ve got this in my Facelet:

<body onload="updateColorInfo()">
  <h:form>
    <h:inputHidden value="#{userPrefs.screenColorDepth}" id="screenDepth" />
  </h:form>

The problem is, JSF changes the element IDs when it processes the page. So how do I correctly target these elements in my JavaScript? What’s the best way to do this?

I’m pretty new to JSF, so any help would be awesome. Thanks in advance!

I’ve tackled this issue before, and here’s what worked for me. Instead of relying on IDs, you can use JSF’s pass-through attributes to add a custom data attribute to your hidden input. Then, use JavaScript to select the element by this attribute. Here’s how:

<h:inputHidden value="#{userPrefs.screenColorDepth}" id="screenDepth" p:data-js-ref="screenDepth" />

In your JavaScript:

function updateColorInfo() {
    var hiddenInput = document.querySelector('[data-js-ref="screenDepth"]');
    if (hiddenInput) {
        hiddenInput.value = screen.colorDepth;
    }
}

This approach is more robust as it doesn’t rely on specific IDs. It’s been a game-changer for me in JSF projects where I needed to interface with JavaScript. Give it a shot and see if it solves your problem!

When working with JSF and JavaScript, you’re right that the IDs can be tricky. One approach I’ve found effective is to use the ‘binding’ attribute in JSF to get a reference to the component, then use that to find the client ID. Here’s how you might modify your code:

<h:inputHidden binding='#{hiddenInput}' value='#{userPrefs.screenColorDepth}' />

Then in your backing bean:

@ManagedBean
@ViewScoped
public class YourBackingBean {
    private HtmlInputHidden hiddenInput;
    
    public String getHiddenInputClientId() {
        return hiddenInput.getClientId();
    }
    // getter and setter for hiddenInput
}

Now you can use EL in your JavaScript to get the correct client ID:

function updateColorInfo() {
    document.getElementById('#{yourBackingBean.hiddenInputClientId}').value = screen.colorDepth;
}

This approach has worked well for me in similar situations. Hope it helps!

hey mate, i’ve dealt with this before. try using f:param to pass the id to ur js function. like this:

<h:form>
<h:inputHidden value="#{userPrefs.screenColorDepth}" id="screenDepth" />
<f:param name="screenDepthId" value="#{component.clientId}" />
</h:form>

then in ur js:

function updateColorInfo(screenDepthId) {
document.getElementById(screenDepthId).value = screen.colorDepth;
}

works like a charm for me. goodluck!