0 votes
in Education by (1.7m points)
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.

JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)

1 Answer

0 votes
by (1.7m points)
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
...