简体   繁体   中英

Pass a value from <% %> to <script> (JSP)

I have the following code, I would like to know if there is a way I can use the variable "prov" in the tag part

   <% 
        String prov;
        if(request.getParameter("btnBusProv")!= null)
        {
            prov = request.getParameter("cbProv");
            out.println("Nombre del proveedor: ");
            out.println(prov);
        }
    %>
    <script>
        function MostrarNombres()
        {
            document.getElementById("txtRUC").value = prov;
            document.getElementById("txtFec").value = prov;
            document.getElementById("txtDIR").value = prov;
        }
    </script>

You can use hidden variables for this purpose, for example:

 <input type="hidden" id="prov" value='<%=request.getParameter("cbProv") %>' >

and then, in the script block:

var obj = document.getElementById("prov");

There's no need to use a hidden input element when all you need is the value of a request parameter. Use ${param.cbProv} to access that value without scriptlets.

<script>
    var prov;
    <c:if test="${not empty param.btnBusProv}">
        prov = '${param.cbProv}';
    </c:if>

    function MostrarNombres()
    {
        document.getElementById("txtRUC").value = prov;
        document.getElementById("txtFec").value = prov;
        document.getElementById("txtDIR").value = prov;
    }
</script>

You can use JSP Expressions:

<script>
    function MostrarNombres()
    {
        document.getElementById("txtRUC").value = <%=prov%>;
        document.getElementById("txtFec").value = <%=prov%>;
        document.getElementById("txtDIR").value = <%=prov%>;
    }
</script>

Or a more straightforward way would be to set it directly in a hidden html dom element and use it:

<input id='prov' type="hidden" value='<%=request.getParameter("cbProv")%>'>

<script>
    function MostrarNombres()
    {
        var prov = document.getElementById('prov').value;
        document.getElementById("txtRUC").value = prov;
        document.getElementById("txtFec").value = prov;
        document.getElementById("txtDIR").value = prov;
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM