I making "select" which options are 'Edit', 'Delete'. When I click "Edit", the page goes to the "edit_product.jsp" well. But when I click "Delete", the page goes to the "edit_product.jsp" again, not "delete_product.jsp". I want to just click select option, which is going other page -"Edit" is "edit_product.jsp", and "Delete" is "delete_product.jsp"-.
Here is the code.
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<% request.setCharacterEncoding("utf-8"); %>
<%# page language="java" import="java.sql.*,java.util.*" %>
<jsp:include page="../basis/basis.jsp" flush="false" />
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" charset="UTF-8">
<link rel="StyleSheet" href="product.css" type="text/css">
<script src="../basis/basis.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".all_check").click(function() { //select all
..
});
$('.edit_select').change(function() {
if ($('.edit_select option[name=edit]:selected')) {
window.location.href="edit_product.jsp?code="+$('.edit_select option[name=edit]:selected').val();
return;
} else if ($('.edit_select option[name=delete]:selected')) {
window.location.href="delete_product.jsp?code="+$('.edit_select option[name=delete]:selected').val();
return;
}
});
});
</script>
</head>
<body>
<div class="hhh">
All Products
</div>
<div class=" add_btn btn-group" role="group">
..
</div>
<center>
<div class="all_product">
<table class="table" data-toggle="table">
<tr>
<th></th>
<th>
check <br />
<input type="checkbox" name="all_check" class="all_check" />
</th>
<th>Product Code</th>
<th>Image</th>
<th>Price</th>
<th>Status</th>
<th>Business Group</th>
<th>Category</th>
<th>Stock</th>
<th>Supplier</th>
<th>Marketplaces</th>
<!--
<th>Added Time</th>
<th>Added User</th>
<th>Modified Time</th>
<th>Modified User</th>
-->
</tr>
<%
Vector product_code = new Vector();
Vector image = new Vector();
Vector price_cny = new Vector();
Vector status = new Vector();
Vector bus_grp = new Vector();
Vector category = new Vector();
Vector stock = new Vector();
Vector supplier = new Vector();
Vector market = new Vector();
Connection con= null;
Statement st =null;
ResultSet rs =null;
String img = "";
String url = "http://localhost/Becomeus/Scripts/Products/image/";
try {
Class.forName("org.gjt.mm.mysql.Driver");
} catch (ClassNotFoundException e ) {
out.println(e);
}
try{
con = DriverManager.getConnection("jdbc:mysql://localhost/becomeus?useUnicode=true&characterEncoding=utf8","root","qlzjadjtm!2");
} catch (SQLException e) {
out.println(e);
}
try {
st = con.createStatement();
String sql = "select * from new_product";
rs = st.executeQuery(sql);
if (!rs.next()) {
out.println("No Product.");
} else {
do {
product_code.addElement(rs.getString("product_code"));
image.addElement(rs.getString("image"));
price_cny.addElement(new Integer(rs.getInt("price_cny")));
status.addElement(rs.getString("status"));
bus_grp.addElement(rs.getString("business_group"));
category.addElement(rs.getString("category"));
stock.addElement(new Integer(rs.getInt("stock")));
supplier.addElement(rs.getString("supplier"));
market.addElement(rs.getString("marketplaces"));
} while(rs.next());
int totalrows = product_code.size();
for (int j=0; j<=(totalrows-1); j++) {
String pro_code = (String)product_code.elementAt(j);
out.println("<tr>");
out.println("<td>"); //select
out.println("<select name='edit_select' class='edit_select selectpicker' data-width='100px'>");
out.println("<option data-hidden='true'>-Select-");
out.println("<option name='edit' value="+product_code.elementAt(j)+">Edit");
out.println("<option name='delete' value="+product_code.elementAt(j)+">Delete");
out.println("<option value='duplicate'>Duplicate");
out.println("<option value='print'>Print");
out.println("<option value='viewrecord'>View Record");
out.println("</select>");
out.println("</td>");
out.println("<td>"); //check box
out.println("<input type='checkbox' name='check' />");
out.println("</td>");
out.println("<td><a href='#' class='product_code'>"+product_code.elementAt(j)+"</a></td>");
out.println("<td><img width=100 height=100 src='image/"+image.elementAt(j)+"' /></td>");
out.println("<td>"+price_cny.elementAt(j)+"</td>");
out.println("<td>"+status.elementAt(j)+"</td>");
out.println("<td>"+bus_grp.elementAt(j)+"</td>");
out.println("<td>"+category.elementAt(j)+"</td>");
out.println("<td>"+stock.elementAt(j)+"</td>");
out.println("<td>"+supplier.elementAt(j)+"</td>");
out.println("<td>"+market.elementAt(j)+"</td>");
out.println("</tr>");
}
rs.close();
}
st.close();
con.close();
} catch (java.sql.SQLException e) {
out.println(e);
}
%>
</table>
</div>
</center>
</body>
</html>
I using jQuery and jsp. Can window.location.href use only one? I using if else if, but no action to else if. How can I use? Please answer to me.
To get the selected value name attribute use this,
if ($(this).find('option:selected').attr("name")==='edit') {
window.location.href="edit_product.jsp?code="+$('.edit_select option[name=edit]:selected').val();
return;
} else if($(this).find('option:selected').attr("name")==='delete') {
window.location.href="delete_product.jsp?code="+$('.edit_select option[name=delete]:selected').val();
return;
}
This should redirect you to the respective pages.
Yes you can use window.location.href any number of times.
MDN window.location.href
window.location.href="edit_product.jsp?code="+$('.edit_select option[name=edit]:selected').val();
You can also use jQuery - load
$( "#result" ).load( "ajax/test.html" );
Related
I need help in passing the values present in the jquery function of a jsp page to a servlet.
I have grouped the set of values present in the checked check box row using the jquery function.Now I need to insert those values into my database. I tried to pass the values using request.getParameterValues(),but it is not working. Kindly help me in passing the stored array values present in the jquery function of my jsp page to the servlet.
This is my jquery function present in the jsp page
<script>
$('#btn').on('click', function() {
var checkedRows = [];
$(':checkbox:checked').closest('tr').each(function() {
checkedRows.push(
$(this).find('td:gt(0)').map(function() {
return $(this).html();
}).get()
);
});
console.log( checkedRows );
});
</script>
JSP page
<%#page import="java.util.List"%>
<%#page import="web.Products"%>
<%#page import="java.util.ArrayList"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript" src="JS/jquery-1.4.2.min.js"></script>
<script>
$('#btn').on('click', function() {
var checkedRows = [];
$(':checkbox:checked').closest('tr').each(function() {
checkedRows.push(
$(this).find('td:gt(0)').map(function() {
return $(this).html();
}).get()
);
});
console.log( checkedRows );
});
</script>
</head>
<form name="sform" method="post" action="Save_Products">
<table style="width:40%">
<tr> <th> Brand Name</th>
<th> Product Name</th>
<th> Description</th>
</tr>
<tr>
<td><%
List<Products> pdts = (List<Products>) request.getAttribute("productlist");
if(pdts!=null){
for(Products prod: pdts){
out.println("<input type=\"hidden\" name=\"brand_name\" value=\"" + prod.getBrandname() + "\">");
out.println("<br/>"+prod.getBrandname());
} %> </td>
<td><%
if(pdts!=null){
for(Products prod: pdts){
out.println("<input type=\"checkbox\" name=\"prod\" checked=\"checked\" value=\"" + prod.getProductname() + "\">" + prod.getProductname()+"<br>");
} } %> </td>
<td><%
if(pdts!=null){
for(Products prod: pdts){
out.println("<input type=\"text\" name=\"desc\" style=\"width:50px; height:22px\" value=\""+prod.getDesc()+"\"/><br/>");
}
}
} %> </td>
</tr>
<br/>
<br/>
<tr>
<td></td>
<td align="center"> <input id="btn" type="submit" value="Save" name="save"/> </td></tr>
</table>
</form>
</html>
try this code for passing js array to servlet :
in your jsp add :
$.post('Save_Products', {arrayData:checkedRows, mode:"insert"});
In your servlet :
String[] arrayData=request.getParameterValues("arrayData[]");
This code below let me delete the row from the table in jsp page but not from my database,how can i do this? In other words i need to delete the row (to my database) whenever is checked a checkbox on my jsp page. i need a dynamicaly delete table row both on database and on jsp page.
<%#page import="java.sql.*" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>destcode</title>
<link rel="stylesheet" type="text/css" href="DELETE BUTTON CSS.css">
</head>
<style> Stable, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
</style>
<%
Class.forName("com.mysql.jdbc.Driver");
String myDatabase = "jdbc:mysql://localhost:3306/project_app?user=root&password=1234";
Connection myConnection = DriverManager.getConnection(myDatabase);
Statement myStatement = myConnection.createStatement();
String search=request.getParameter("search");
ResultSet rs = myStatement.executeQuery("SELECT * FROM DEST WHERE COUNTRY='"+search+"' OR CITY='"+search+"' ");
%>
<table style="width:100%">
<table id="Dest_table">
<tr>
<th> Dest. No. </th>
<th>Check </th>
<th>Country</th>
<th>City</th>
<th>Url of Destination</th>
<th>Category</th>
</tr>
<tr> <%while(rs.next()){ %>
<td> <%=rs.getString("ID_DEST") %> </td>
<td><INPUT type="checkbox" name="chk" value="checked"/></td>
<td> <%=rs.getString("COUNTRY") %></td>
<td> <%=rs.getString("CITY") %> </td>
<td> <a href=<%=rs.getString("URL") %> > <%=rs.getString("URL") %> </a>
</td>
</tr>
<% } %>
</table>
<SCRIPT language="javascript">
function deleteRow(Dest_table) {
try {
var table = document.getElementById(Dest_table);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</SCRIPT>
DataTables spring mvc support
I am using one Weblogic data source, I am ultimately attempting to retrieve one record at a time from the Weblogic data source and then display that record in a data table also one at a time. DataTables.net has an example called "add rows" but it does not accommodate using getting data from data sources. The empty data table displays on the webpage, I can see the query running correctly to the data source however the record is not displaying in the data table.
I included the following in my code:
<script src="<c:url value="/resources/js/jquery.js" />"></script>
<script src="<c:url value="/resources/js/jquery.min.js" />"></script>
<script src="<c:url value="/resources/js/jquery.dataTables.min.js" />"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.css"/>
Snippet from CONTROLLER:
#RequestMapping(value = "/locate", method = RequestMethod.GET)
public #ResponseBody NewOrder getModelYearAndVehicleOrder(
#RequestParam(value="modelYear") String modelYear\,
#RequestParam(value="vehicleOrder\") String vehicleOrder\){
if (modelYear\.isEmpty() || vehicleOrder\.isEmpty())
throw new IllegalArgumentException("Try Again!");
NewOrder newOrder;
try {
newOrder= OrderRepo.findNewOrderByModelYearAndVehicleOrder(modelYear, vehicleOrder);
}
catch (Exception e){
#SuppressWarnings("deprecation")
Throwable _e = ExceptionUtils.getCause(e);
throw new ExceptionHandler(
DatabaseMessage.RETRIEVE_ERROR.toString(), _e.getMessage());
}
return newOrder;
}
HTML:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<body>
<h1>Template Spring MVC App</h1>
<form id= "locateVehicle">
<p> Model Year? <input id="modelYear" type="text" th:field="*{modelYear}" /> </p>
<p> Order? <input id="orderNum" type="text" th:field="*{vehicleOrder}" /> </p>
<button onclick="goToDetails()">Locate</button>
</form>
<br></br>
<div class="row">
<div class="col-lg-12">
<table id="list" class="display">
<thead>
<tr>
<th>Model Year</th>
<th>Order #</th>
<th>Model</th>
</tr>
</thead>
<tbody>
<c:forEach var="order" items="${order}" varStatus="loop">
<tr>
<td><c:out value="${order.modelYearNbr}" /></td>
<td><c:out value="${order.vehicleOrderNm}" /></td>
<td><c:out value="${order.model}" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
JS:
<script>
$(document).ready( function () {
$('#list').DataTable();
} );
function goToODetails() {
var modelYear = $('#modelYearId').val();
var vehicleOrder = $('#vehicleOrderId').val();
var url = './DataLoader/locate?modelYear=' + modelYear + '&vehicleOrder' + vehicleOrder;
$.get(url,function(result) {
var vehicle = result;
var list = $("#list");
list.append('<tr><td>' + result.modelYearNbr + '</td>' +
'<td>' + result.vehicleOrderNm + '</td>' +
'<td>' + result.model + '</td></tr>');
});
}
</script>
Before I added the data table files I was able to see the record post to the webpage, now it is not posting to the table.
Finally got it working, here is how:
$(document).ready(function() {
var table = $('#orderList').DataTable()
$('#goToOrder').on('click', function() {
var modelYear = $('#modelYearId').val();
var url = './DataLoader/locate?modelYear=' + modelYear;
$.get(url, function(result) {
$(result).each(function( i, object ){
var vehicle = result[i];
table.row.add([
vehicle.modelYear,
vehicle.vehicleOrder,
vehicle.model
]).draw(false)
.nodes()
.to$();
})
})
})
});
i am trying to retrieve values from jsp using ajax as explained here here . but its not returning the values from the DB.Please help with this
home page
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Jsp Page</title>
<script>
function showuser(str)
{
var xreq;
if (str == "")
{
document.getElementById("showtext").innerHTML = "";
return;
}
if (window.XMLHttpRequest)
{
xreq = new XMLHttpRequest();
}
else
{
xreq = new ActiveXObject("Microsoft.XMLHTTP");
}
xreq.onreadystatechange = function()
{
if ((xreq.readyState == 4) && (xreq.status == 200))
{
document.getElementById("showtext").innerHTML
= xreq.responseText;
}
}
xreq.open("get", "getuser.jsp?q=" + str, "true");
xreq.send();
}
</script>
</head>
<body>
<form>
<select name="user" onchange="showuser(this.value)" >
<option value="">Select Student name....</option>
<option value="abhi">abhi</option>
<option value="alex">alex</option>
<option value="adam">adam</option>
</select>
</form>
<br/>
<div id="showtext">The response will come here</div>
</body>
</html>
DB connection establishment page
<%#page import="java.text.SimpleDateFormat"%>
<%#page import="java.util.*,java.sql.*,java.io.*" %>
<%#page import="javax.servlet.*" %>
<%#page import="javax.servlet.http.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jsp Page</title>
</head>
<body>
<%! Connection con;%>
<%! Statement s;%>
<%! ResultSet rs;%>
<% String name = request.getParameter("st");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("URL");
s = con.createStatement();
rs = s.executeQuery("select * from studentinfo where name='" + name + "'");
} catch (Exception e) {
e.printStackTrace();
}
%>
<div id="dtl_table"><table border='3' cellpadding='5'
cellspacing='2' width="400px">
<tr bgcolor="66FF00">
<th>Name</th>
<th>Branch</th>
<th>Year</th>
<th>Email id</th>
</tr>
<tr>
<% while (rs.next()) {
%>
<td><%= rs.getString("NAME")%></td>
<td><%= rs.getString("BRANCH")%></td>
<td><%= rs.getString("YEAR")%></td>
<td><%= rs.getString("EMAIL")%></td>
<% }%>
</tr>
</table></div>
</body>
</html>
Table structure
CREATE TABLE studentinfo(
name VARCHAR2(30),
branch VARCHAR2(20),
year VARCHAR2(20),
email VARCHAR2(80)
);
There is no parameter st in the request Object
String name=request.getParameter("st");
The parameter you are passing is q
xreq.open("get","getuser.jsp?q="+str,"true");
I have created a simple site that reads a database table and displays it in a html table in the browser.
I have a button that allows for the table to be altered, saved & then automatically forwarded to the homepage with the updated table.
I also have a select button with which the user can select that particular row and it updates a column in the table.
My problem is that I need a way to show which row has been selected.
I prefer to have a column in the HTML table that shows an image as to which one is selected.
Here is my homepage where the database table is being displayed.
In the left column of the html is where I would like to add an image if that row is selected.
I have tried several things like using javascript and just can't wrap my head around it?
Can I get some help?
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.io.*, java.util.*, java.sql.*"%>
<%#page import="oracle.jdbc.driver.OracleConnection" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript">
function editRecord(id) {
var f=document.form;
f.method="post";
f.action='edit.jsp?id='+id;
f.submit();
}
function selectRecord(id, btn, i) {
var f=document.form;
f.method="post";
f.action='select.jsp?id='+id;
f.submit();
if(!btn.style) {
alert("not supported");
return;
} else{
btn.style.background = "red";
return;
}
}
</script>
</head>
<body>
<br><br>
<form method="post" name="form">
<table id="data" border="1">
<tr>
<th>Selected</th>
<th>Name</th>
<th>Address</th>
<th>Contact No</th>
<th>Email</th>
<th>Select</th>
</tr>
<%
int sumcount=0;
ResultSet rs = null;
Connection con = null;
Statement st = null;
try {
DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "username", "password");
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM employee");
%>
<%
while(rs.next()) {
%>
<tr>
<td></td>
<td><%=rs.getString(2)%></td>
<td><%=rs.getString(3)%></td>
<td><%=rs.getString(4)%></td>
<td><%=rs.getString(5)%></td>
<td><input type="button" name="edit" value="Edit" style="background-color:#49743D;font-weight:bold;color:#ffffff;" onclick="editRecord(<%=rs.getString(1)%>);" /></td>
<td><input type="button" name="select" value="Select" style="background-color:#49743D;font-weight:bold;color:#ffffff;" onclick="selectRecord(<%=rs.getString(1)%>, this);" /></td>
</tr>
<%
}
%>
<%
}
catch(Exception e){
e.printStackTrace();
}
%>
</table>
</form>
</body>
</html>
<script language="javascript">
function editRecord(id) {
var f=document.form;
f.method="post";
f.action='edit.jsp?id='+id;
f.submit();
}
function selectRecord(id, btn, i) {
//Here goes the code to display image
var images = document.getElementsByName("selectImg");
for(var i=0;i<images.length;i++){
if(images[i].id!="img_"+id)
images[i].style.display="None";
else
images[i].style.display="Block";
}
//End
var f=document.form;
f.method="post";
f.action='select.jsp?id='+id;
f.submit();
if(!btn.style) {
alert("not supported");
return;
} else{
btn.style.background = "red";
return;
}
}
</script>
You need to put a hidden div with image in first column.
<%
while(rs.next()) {
%>
<tr>
<td><div name="selectImg" id="img_<%=rs.getString(1)%>">
<img src="path_to_image"></div></td>
<td><%=rs.getString(2)%></td>
<td><%=rs.getString(3)%></td>
<td><%=rs.getString(4)%></td>
<td><%=rs.getString(5)%></td>
<td><input type="button" name="edit" value="Edit" style="background-color:#49743D;font-weight:bold;color:#ffffff;" onclick="editRecord(<%=rs.getString(1)%>);" /></td>
<td><input type="button" name="select" value="Select" style="background-color:#49743D;font-weight:bold;color:#ffffff;" onclick="selectRecord(<%=rs.getString(1)%>, this);" /></td>