Iam trying to access a scriplet variable in my javascript function,but i am not getting resul as expected, here is my javascript,
<script language="javascript">
function drawFreeSlot(){
var div = document.createElement('div');
var slotNo = <%=slotCount%>;
div.className = 'col-1';
//div.appendChild("Slot"+slotNo);
div.style.backgroundColor = 'lightgreen';
document.getElementById('content').appendChild(div);
</script>
and my scriplet code as ,
<%!int slotCount = 0; %>
<%for(ParkingSlot slot:slotList){
if(slot.getPhoneNo() == 0){
slotCount++;%>
<script>
drawFreeSlot();
</script>
<%
}%>
both code are in same jsp file, Please help me,Thanks in advance.
To understand your problem, you need some informations on the way this is done.
Your are working with two different side in your code. The scriplet on the server side and the javascript on client side, First the scriplet is executed then the result is send to the browser to execute the javascript.
Server side
The first thing to understand is that the Scriplet will not execute Javascript code. The JSP will basicly add some text into the file.
In your case, your loop will insert
<script>
drawFreeSlot();
</script>
For each ParkingSlot with a phone number at 0. (and increment the variable).
It will also insert the variable value into the function
<script language="javascript">
function drawFreeSlot(){
var div = document.createElement('div');
var slotNo = <%=slotCount%>;
div.className = 'col-1';
//div.appendChild("Slot"+slotNo);
div.style.backgroundColor = 'lightgreen';
document.getElementById('content').appendChild(div);
</script>
The values will depend on the position of this code, if this is after the loop, you will have the number of slot, if not, it will be 0. It doesn't use the variable, just insert the value as text.
Client side
When this is done, the page will be send to the Client browser and receive an HTML page with a those script block.
The browser will read the file to show the result. This is when the Javascript is execute. So for each drawFreeSlot()
block found, he will execute the function, but the function only have the value of the variable insert at the time, this is where is your problem.
Solution
As nnnnnn suggest it,passing using a parameter will fix the problem.
<script>drawFreeSlot(<%=++slotCount%>);</script>
The HTML page will look like :
...
<script>
drawFreeSlot(1);
</script>
...
<script>
drawFreeSlot(2);
</script>
...
<script>
drawFreeSlot(3);
</script>
...
Just a simple change in the function to work with this parameter is need and your code will work.
Since on each loop, you print the value at this time of your variable.