How to use JSTL var in Jquery selector

2019-04-02 14:27发布

问题:

I am using following Jquery selector

$("#selectedQuery td input:radio").attr('checked', true);

Where selectedQuery is a JSTL variable declared as

<c:set var="selectedQuery" value="${dataRequestForm.queryMasterId}" />  

I tested the selector with hard coded values and it's working fine but no luck when used with selectedQuery.
How can we use JSTL <c:set> var in Jquery ? Is there any work around ?

回答1:

In a JSP:

<c:set var="selectedQuery" value="${dataRequestForm.queryMasterId}" />  

<script>
    $("#${selectedQuery} td input:radio").attr('checked', true);
</script>


回答2:

Mixing JSTL code in with the JavaScript can cause your code to become really jumbled. If it's unavoidable, I have all my JSTL variables set to JavaScript variables in one place:

<c:set var="selectedQuery" value="${dataRequestForm.queryMasterId}" />
<script type="text/javascript">
    //NOTE: we are sure 'selectedQuery' does not contain any double-quotes,
    // but most values will need to be escaped before doing this.
    var selectedQuery = "${selectedQuery}";

    // etc.
</script>

...

<script type="text/javascript">
    $("#" + selectedQuery + " td input:radio").attr('checked', true);
</script>


回答3:

I do stuff like that all the time. The JSP parser doesn't know or care about the difference between the contents of a <script> tag (whether using jQuery or not) and any other content in the JSP page.

It should work fine if you do:

<c:set var="selectedQuery" value="${dataRequestForm.queryMasterId}" />

...

<script>
    $("#${selectedQuery} td input:radio").attr('checked', true);
</script>

Note that this requires that the <script> element with your jQuery selector be inside of the same page/JSP scope as your <c:set>. If they aren't in the same scope then of course this will not work.