Reputation: 627
I have a javascript function that takes two parameters: The first one if the ID of a given html division, and the second one is the content of a row of resultSet (returned from the DB).
function displayItem(item_ID, content)
{
alert(typeof(item_ID)); // this one returns a String
el = document.getElementById(item_ID);
alert(el);
dispArea=document.getElementById("individual");
dispArea.innerHTML=content;
}
The problem comes when I try to call the function in one of my links:
<ul id="principle_items">
<!-- <%int x=0; %> !-->
<c:set value ="0" var="x" />
<c:forEach var="row" items="${result.rows}">
<c:set value ="${x+1}" var="x" />
<!-- <% out.println("the value of X is " + x +"\n");%> !-->
<li><a id="${x}" href="#" onclick="displayItem(this.id,'${result.rows[8].PRNCPL_NAME}');"><c:out value="${row.PRNCPL_NAME}"/></a></li>
</c:forEach>
</ul>
instead of selecting reslut.rows[8], I want the index to be the integer value of this.id (all my IDs are "1", "2", "3"...)
onclick="displayItem(this.id,'${result.rows[8].PRNCPL_NAME}');"
when I tried onclick="displayItem(this.id,'${result.rows[this.id].PRNCPL_NAME}');" it did not work obviously because this.id is a string. I know I can use parseInt in Java, but I I am not sure how to do if here within the same statement.
Upvotes: 0
Views: 2770
Reputation: 4216
Use parseInt
function
alert(typeof(parseInt(item_ID)));
//should be "number"
DEMO
var item_ID = "7";
alert(typeof(parseInt(item_ID)));
Upvotes: 2
Reputation: 4584
You'll want to use the parseInt
as described in Tareq Mahmood's answer but the parseInt
function also accepts a radix which causes values to always be calculated using that base preventing potential errors when reading certain numbers like 08
for instance.
From MDN:
radix
An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above mentioned string. Specify 10 for the decimal numeral system commonly used by humans. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified, usually defaulting the value to 10.
Your function becomes this:
function displayItem(item_ID, content) {
var item_ID = parseInt(item_ID, 10);
alert(typeof(item_ID)); // this one returns a String
el = document.getElementById(item_ID);
alert(el);
dispArea = document.getElementById("individual");
dispArea.innerHTML=content;
}
Should you have to work with decimal numbers then there's it's brother parseFloat
that might be able to help you out.
Upvotes: 0
Reputation: 1104
I think the issue is with parsing of JSP and JavaScript. They are done at different times. So you can't run JavaScript at JSP parsing time.
So your ID is just ${x}, can you not just put x into your code like this...
onclick="displayItem(this.id,'${result.rows[x].PRNCPL_NAME}');"
Or something similar?
Upvotes: 1