简体   繁体   中英

JavaScript: How to read an input id with a jsp tag inside (id=“studenttid_<%=intCount%>”)

Let say I have 10 students.

I declared a variable, intCount=0 so that I can loop the input field with their respective id.

The code for the looping input field looks like this:

<%intCount++%>
<tr>
  <td><input type="text" id="studenttid_<%=intCount%>"%>"></td>
</tr>

After compilation, the output is:

studentid_1
studentid_2
studentid_3
studentid_4
studentid_5
studentid_6
studentid_7
studentid_8
studentid_9
studentid_10

Then, I need to parse the studentid_1,...,studentid_10 to my javascript, which the problem is I do not know what should I write in document.getElementById('') .

I tried something like:

<script>var studentId = document.getElementById('studentid_<%=intCount%>')</script>

but it returns "variable intCount is undefined". What should I do to solve my problem? Please help. Thanks in advance.

You can do the following:

  1. Get all input fields.
  2. Filter that list for the ones that have an ID like what you are looking for.
  3. Get the id property from the ones you are looking for.

You could do this with .reduce instead of .filter().map() but this is probably simpler to understand.

 var inputs = document.getElementsByTagName("input"); var inputArr = Array.apply(null, inputs); var studenttid_elements = inputArr.filter(ele => ele.id.indexOf("studenttid_") === 0); var studenttid_ids = studenttid_elements.map(ele => ele.id); console.log("Elements:", studenttid_elements); console.log("IDs", studenttid_ids); 
 <input type="text" id="studenttid_1"> <input type="text" id="studenttid_2"> <input type="text" id="other_id"> 

You need to keep your JavaScript code within a <script> tag in a JSP file or in a file included in a JSP file.

<script>var studentId = document.getElementById('studenttid_<%=intCount%>') </script>

If your JavaScript is not within a tag or not within a JSP file, the Jasper engine will ignore it.

Alternately, just use EL.

'studenttid_${intCount}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM