Short version: How can I (using a JQuery or other selector) select an HTML element created by this instance of a JSP 2.0 tagfile, which may be used multiple times per page?
Long version:
I have a JSP 2.0 tagfile, like so:
<%@ tag body-content="empty" import="org.myapp.model.Question" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ attribute name="question" required="true" type="org.myapp.model.Question" %>
<div class='singleChoice'>
<c:forEach items="${question.questionOptions}" var="option">
<!-- display options... -->
</c:forEach>
</div>
This tag may be used multiple times on a given page. If the size of question.questionOptions is less than 3, I want to add an additional CSS class (‘compact’) to the ‘singleChoice’ div produced by this tag. I would like to add logic to the tagfile (JavaScript, additional JSTL, whatever is necessary) to check the length of questionOptions and add the class to the div if necessary.
I know that I can add a script tag to the tagfile, like so:
<c:if test="${fn:length(question.questionOptions) < 3}">
<script type="text/javascript">
$(document).ready(function() {
$('div .singleChoice').addClass('compact');
});
</script>
</c:if>
but since that executes when the entire document is ready, and the tag may appear multiple times in a page, it will apply the ‘compact’ class to ALL ‘singleChoice’ divs on the page if any of them meet the criteria for applying it. How can I specify this div from within the tagfile, when I don’t know the ID (and would like to avoid having to set it)?
Do you want to add a class “compact” if
${question.questionOptions}is less than three? If yes, my proposed solution is to add a condition that set the div with class=”singleChoice compact”.This solution is not tested, though the logic is there if I understood question your correctly.