dongcheng dongcheng - 1 month ago 7
jQuery Question

How to read data from dynamically created textbox in jsp using jQuery.each()

I have textbox that created dynamically in jsp. Then, I want to take the data inside and send it to servlet using jQuery.each(). The problem is, it only takes top textbox data only and not even read the rest. Can someone point out the problems.Btw, english not my native.

Dynamically created textbox,

<table>

<c:forEach items="${questList}" var="quest" varStatus="status">

<tr id="looping">
<td><c:out value="${status.index + 1}" ></c:out></td>
<td>${quest.questText}</td>
<td><textarea id="resp" rows="5" cols="40"></textarea></td>
<td><textarea id="qId" >${quest.questId}</textarea></td>
</tr>
</c:forEach>
</table>


and my jQuery code

$('#looping').each(function(i){
var res = $('#resp').val();
var qId = $('#qId').val();

$.ajax({
type:'POST',
data:{
res: res,
qId: qId,
},
url:'Response'

})
});

Answer

You should change your code to look like this, because when trying to get data by targeting the field with an ID selector will only return the data from the first field. So change your code to look like this:

('#looping').each(function(i){
        var res = $(this).find('#resp').val();
        var qId = $(this).find('#qId').val();

        $.ajax({
            type:'POST',
            data:{
                res: res,
                qId: qId,
            },
        url:'Response'

        })
    });