Search code examples
javascriptjqueryhtmljspstruts2

javascript not working on struts html tag


I have the following codes in a jsp page in my Struts2 project

<select id="amountSelect">
 <s:iterator value="rateCardDetailsList" status="listStatusAmount">
    <option value="<s:property value='#listStatusAmount.index'/>"><s:property value="rechargeAmount"/></option>
</s:iterator>
</select>

and a corresponding script for this

 $(document).ready(function() {
    $("#amountSelect").change(function(){
        var v= $("#amountSelect").val();
        var r= "<s:property value='rateCardDetailsList["+ v +"].mobileRate'/>";
        alert(r);
    });
});

where rateCardDetailsList is an array of a particular bean(Object) which contain the variable mobileRate. But I'm getting null at the position of r whil alerting (alert(r);). On inspecting the element it was as following

 $(document).ready(function() {
        $("#amountSelect").change(function(){
            var v= $("#amountSelect").val();
            var r= "";
            alert(r);
            
        });
    });

Instead of the variable v if I direcly give the index I'm getting the value i.e

 var r= "<s:property value='rateCardDetailsList[1].mobileRate'/>";
    alert(r);

does gives a value in the alert. What coud be the reason?


Solution

  • This is wildly invalid JSP + JavaScript:

    var r = "<s:property value='rateCardDetailsList["+ v +"].mobileRate'/>";
    

    Take a step back and think about where all this code is executing.

    JSP, e.g., custom tags (here the <s:property> tag) is evaluated on the server side, before anything is sent to the browser.

    JavaScript is executed on the client side, after being rendered on the server and sent to the client. Here you're trying to mix server side code (the tag) with JavaScript code, the string concatenation. Won't even come close to working.

    To get this to work you need to render valid JavaScript on the server side, or use Ajax and get the JS values dynamically, etc. It's common to render JS data structures (e.g., JSON), but there are many other options.