Showing posts with label JSP. Show all posts
Showing posts with label JSP. Show all posts

Monday, June 16, 2008

Pass values between java and javascript

add java to javascript:-

<script type="text/javascript" xml:space="preserve">
document.getElementById("latitude").value="<%=latitude%>";
document.getElementById("longitude").value="<%=longitude%>";
alert(document.getElementById("longitude").value);
</script>


add javscript to java:-

<%
String selectForAdd;
selectForAdd = "javascript:document.personViewForm.PKpersonItemType.value='javascript:document.personViewForm.personType.value';";
selectForAdd += "document.personViewForm.PKpersonItemCode.value='javascript:document.personViewForm.personItemCode.value';";
selectForAdd +="document.personViewForm.PKpersonItemLang.value='javascript:document.personViewForm.personItemLang.value';";
selectForAdd +="document.personViewForm.pageMode.value='addChild';";
%>

Then we can send this variable in a button click
<input type="button" name="select" onClick="<%= selectForAdd%>" />


add strtus to javascript:-

<bean:define name="res" property="bkClasses" id="selectedClass"/>
<script>
oldBkClasses[oldBkClasses.length]='<bean:write name="selectedClass"/>';
</script>

To access a javascript value at the server end:-

create a hidden field on the jsp and set it with the desired value. This will be submitted to the server as a request parameter

Friday, June 13, 2008

Using JSTL tags with struts and javascript

We can use jstl tag library and struts together to get rich programming

For this you need to import java.sun.com/jstl/core_rt" prefix="c" in your jsp

<c:set var="displayOption" value="${0}"/>

<nested:iterate id="serviceRepStn" name="resultList" property="stations" indexId="indexId">
<c:set var="displayOption" value="${indexId}"/>

<td>
<nested:text property="srrpStops" styleClass="stops" readonly="true"
styleId="stops${displayOption}"/>
</td>


//We can access the text element in javascript as below

var stopsCollect = document.forms[0].elements["stops${displayOption}"];

// If the text fields are dynamically generated and we do not know whether an array of srrpStops or single element will be passed to us in the request, we can handle it as below

var sum = 0;

var stopsCollect = document.forms[0].elements["stops${displayOption}"];
if(stopsCollect.length == undefined)
{
stopsCollect = document.forms[0].stops${displayOption-1};
if (!isNaN(parseFloat(stopsCollect.value)))
{
sum += parseFloat(stopsCollect.value);
alert("Sum : " + sum);
}
}
else
{
for (var i = 0; i < stopsCollect.length; i++)
{
if (!isNaN(parseFloat(stopsCollect[i].value)))
{
sum += parseFloat(stopsCollect[i].value);
}
}

}