How to highlight a row in JSF table on link click using JavaScript?

I’ve got a JSF datatable with a column containing a command link. I need to make the row’s background change color when someone clicks the link. Here’s what my column looks like:

<x:column id="person" width="10%" class="data_col">
  <f:facet name="header">
    <h:outputText value="#{labels.person_name}" />
  </f:facet>
  <x:commandLink action="#{viewModel.selectPerson(person)}" 
                 onajaxend="updatePersonInfo();">
    <h:outputText style="color:#4B0082;" value="View Details" />
  </x:commandLink>
</x:column>

Any tips on how to make this work with JavaScript or jQuery? I’m not sure where to start.

I’ve encountered this scenario before in a project. Here’s what worked for me:

Instead of modifying the JSF component directly, I found it more maintainable to use jQuery. First, add a unique identifier to your commandLink:

<x:commandLink id=“personLink#{person.id}” action=“#{viewModel.selectPerson(person)}”
onajaxend=“updatePersonInfo();”>

Then, in your JavaScript file or script tag:

$(document).ready(function() {
$(‘[id^=personLink]’).click(function(e) {
e.preventDefault();
$(this).closest(‘tr’).addClass(‘highlighted’);
$(‘.highlighted’).not($(this).closest(‘tr’)).removeClass(‘highlighted’);
});
});

Define the ‘highlighted’ class in your CSS:

.highlighted { background-color: #ffff99; }

This approach keeps your JSF clean and separates concerns. It also allows for easy modification of the highlight behavior without touching the server-side code.

hey, I had a similar issue. try adding an onclick event to ur commandLink like this:

onclick="highlightRow(this); return false;"

then make a js function:

function highlightRow(link) {
  link.closest('tr').style.backgroundColor = 'yellow';
}

this shud do the trick! lmk if u need more help

To highlight the row when the link is clicked, you can leverage JavaScript and DOM manipulation. Here’s an approach you might consider:

  1. Add an onclick event to your commandLink that calls a JavaScript function.
  2. In that function, use DOM traversal to find the parent row of the clicked link.
  3. Apply a CSS class to that row for highlighting.

You could modify your commandLink like this:

<x:commandLink action=\"#{viewModel.selectPerson(person)}\" 
               onajaxend=\"updatePersonInfo();\"
               onclick=\"highlightRow(this); return false;\">
  <h:outputText style=\"color:#4B0082;\" value=\"View Details\" />
</x:commandLink>

Then create a JavaScript function:

function highlightRow(link) {
  var row = link.closest('tr');
  row.classList.add('highlighted-row');
}

Don’t forget to define the ‘highlighted-row’ class in your CSS. This solution should work across different browsers and JSF implementations.