开发者

How to use JSTL var in Jquery selector

开发者 https://www.devze.com 2023-03-29 12:43 出处:网络
I am using following Jquery selector $(\"#selectedQuery td input:radio\").attr(\'checked\', true); Where selectedQuery is a JSTL variable declared as

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 ?


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>


In a JSP:

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

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消