Issue
I am trying to get the value of the input
tag which has the id b_quantity
field but I am getting only the first row b_quantity
value when the data is generated in the table. Every row has a different record and a button when the button has clicked the value of b_quantity
inside this row should be targeted and not the first row the same goes for all other rows. If there is any JQuery
or JS
code I am willing to add it to my JSP page.
Expected Output:
When clicking the Order
button the value of b_quantity
in the same row should be sent to the servlet post method.
Observed Output:
When clicking the Order
button the value of b_quantity
in the first row is sent to the servlet post method.
<tbody>
<%
List<Beverage> beverages = (List<Beverage>) request.getAttribute("beverageList");
for(Beverage b: beverages) {
%>
<tr>
<td class="pt-3-half"><%= b.getName() %></td>
<td class="pt-3-half"><%= b.getManufacturer() %></td>
<td class="pt-3-half"><%= b.getQuantity() %></td>
<td class="pt-3-half"><%= b.getPrice() %></td>
<% if (b.getIncentiveDTO() != null){ %>
<td class="pt-3-half"><%= b.getIncentiveDTO().getName() %> </td>
<%}else { %>
<td></td>
<%}%>
<td>
<input id="b_quantity" type="number" class="b_quantity" min="0" max="<%=b.getQuantity()%>" value="0">
</td>
<td>
<input type="hidden" name="b_id" value="<%= b.getId() %>">
<!-- <input id="q_val" type="hidden" type="number" name="q_val" value="0"> -->
<a id="<%= b.getId() %>" href="" type="button" class="order btn btn-primary btn-lg">Order</a>
</td>
</tr>
<% } %>
</tbody>
I am using AJAX
to invoke the Servlet
doPost method.
<script type="text/javascript">
$(document).ready(function() {
$(".order").click(function() {
event.preventDefault();
$.ajax({
url: '/frontend/new?b_id=' + event.target.id ,
type: 'Post',
data: {
b_quantity: $('#b_quantity').val()
},
success: function(response) {
location.href = "/frontend/beverages";
}
});
});
});
</script>
Solution
The ID b_quantity is not unique because you are generating rows in a table, each each row contains an input with the id b_quantity. Since the input also has the class 'b_quantity', you can use that to find the input. Try this in your click handler:
<script type="text/javascript">
$(document).ready(function() {
$(".order").click(function() {
event.preventDefault();
var myRow = $(this).parents('tr');
var quantity = $('.b_quantity',myRow).val();
$.ajax({
url: '/frontend/new?b_id=' + event.target.id ,
type: 'Post',
data: {
b_quantity: quantity
},
success: function(response) {
location.href = "/frontend/beverages";
}
});
});
});
</script>
Answered By - jalynn2
Answer Checked By - David Marino (JavaFixing Volunteer)