Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use array in getElementById?

I am working on a project where I need to use array values in the getElementById() in javascript. I tried various things, but the code isn't working. Please help me.

I have an array of values like this:

 var examStateArr=["examState1","examState2","examState3","examState4","examState5","examState6","examState7"];

and i use it in getElementById() as:

document.getElementById(examStateArr[str1-1]).value.innerHTML=xmlHttp.responseText

But this doesnt work.

The code works just fine when I hard code values like document.getElementById("examState1"); but not when i use the array.

str1 is an integer that I pass from a jsp file below:

<%for (int j = 1; j < 8; j++) {%>
<tr>
<select  name='examCountry<%= j%>' onchange=showExamState(<%= j%>,this.value);>  
<option value="none" selected="selected">SELECT</option>
<% for (i = 0; i < countrySize; i++) {%>
<% country = (String) countryArr.get(i);%>
<option  value=<%= country%>><%= country%></option>
<% }%>
</select> 


</td>
<td id='examState<%= j%>'>
<select name='examState<%= j%>'>  
<option value='none'>Select</option>
</select>
</td>

Please correct my mistake.

Thank you in advance.

like image 341
Lavanya Mohan Avatar asked Sep 08 '25 03:09

Lavanya Mohan


2 Answers

var examStateArr = ["examState1", "examState2", "examState3", "examState4", "examState5", "examState6"];

for (var i = 0; i < examStateArr.length; i++) {
    document.getElementById(examStateArr[i]).innerHTML = xmlHttp.responseText   
}

Mistake one done by you

document.getElementById('').value.innerHTML   -- is wrong
document.getElementById('').innerHTML         -- is correct

Edit 2

make sure you call this function after DOM is loaded, try adding your script at the bottom

like image 128
Praveen Prasad Avatar answered Sep 10 '25 05:09

Praveen Prasad


You haven't shown us what str1 is but it must be the problem.

For example, try:

document.getElementById(examStateArr[0])

And that should work fine. Array access is zero-based and you have six elements, so the valid values for [n] are 0-5.

It's also possible your array doesn't contain what you think it contains. Before wondering why docuemnt.getElementById isn't working, you should first make sure that what you are passing in is what you expected. Use alert, or with Firebug console.log to output the value you are passing in:

alert(examStateArr[str1 - 1]);
alert(examStateArr[0]);
alert(examStateArr);
like image 35
Nicole Avatar answered Sep 10 '25 04:09

Nicole