Issue
I tried to send Value from Table to Servlet. But its always take value from the first row. my value came from "data-whatever" attribute in Anchor tag on the table cell.
Here is my Table HTML Code
<%
int i = 1;
Session s = DB.getSession();
Criteria cr = s.createCriteria(Branch.class);
List <Branch> branch = cr.list();
for (Branch b: branch) { %>
<tr>
<td><%= i++ %></td>
<td><%= b.getBranchNo() %></td>
<td><%= b.getBranchName() %></td>
<td><%= b.getContact1() %></td>
<td><%= b.getContact2() %></td>
<td><%= b.getCity() %></td>
<td><%= b.getIsActive() %></td>
<td>
<div class="col-md-3"><a href="#" id="viewModal" data-toggle="modal" data-target="#exampleModal" data-whatever="<%= b.getIdBranch() %>" onclick="load()">View</a></div>
<div class="col-md-3"><a href="#">Delete</a></div>
</td>
</tr>
<%
}
%>
</tbody>
And Here is my Script
var BranchID = $('#viewModal').attr('data-whatever');
$('#branchcode1').attr('value',BranchID);
$.ajax({
url : '../BranchViewAJAX',
data : { branchID : BranchID },
success : function(responseText) {
$('#bNo').text(responseText);
BranchID = null;
}
});
Here is the Table Table
Solution
this is simple:
but you must know the priciple first:
ID an CLASS is different. ID is unique so you must use 1 specific ID to only 1 element. CLASS is general. you can use class in a lot of element
so remove id="viewModal"
and add class="viewModal"
in your code, so your code will look like this:
<div class="col-md-3"><a href="#" class="viewModal" data-toggle="modal" data-target="#exampleModal" data-whatever="<%= b.getIdBranch() %>" onclick="load()">View</a></div>
then write script to check this
$('body').on('click', '.viewModal', function(){
var branchID = $(this).attr('data-whatever');
alert(branchID);//do your ajax
});
but if you want still using id="viewModal"
like this
<div class="col-md-3"><a href="#" class="viewModal" data-toggle="modal" data-target="#exampleModal" data-whatever="<%= b.getIdBranch() %>" onclick="load()">View</a></div>
we can use this selector:
$('body').on('click', 'div[id="viewModal"]', function(){
var branchID = $(this).attr('data-whatever');
alert(branchID); //do your ajax
});
Answered By - plonknimbuzz