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>
Related
<html>
<head>
<title>View Shopping Cart</title>
<script type="text/javascript">
function remove(book_id)
{
document.getElementById('bookId').value = book_id;
document.forms[0].submit();
}
</script>
</head>
<body>
<table border="1" id="bookTable">
<tr>
<th>Book ID</th>
<th>Book Name</th>
<th>Author</th>
<th>Quantity</th>
<th>Remove from cart</th>
</tr>
<%
try
{
int cus_id = Integer.parseInt(session.getAttribute("cusId").toString());
ResultSet rs = SqlConnection.getData("select * from book b, shopping_cart s where s.book_id=b.book_id AND s.cus_id=" + cus_id);
if (!rs.first())
{
out.print("<h3>Nothing in the Cart!</h3>");
}
else
{
rs.previous();
while (rs.next())
{
%>
<tr>
<%
out.print("<td>" + rs.getInt("book_id") + "</td>");
out.print("<td>" + rs.getString("book_name") + "</td>");
out.print("<td>" + rs.getString("author_name") + "</td>");
out.print("<td><input type='number' name='qty' id='qty'/></td>");
out.print("<td><input type='button' onClick='remove(" + rs.getInt("book_id") + ")' value='Remove from cart'/></td>");
%>
</tr>
<%
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
%>
</table><br/><br/>
<p style="color: green;">${successful}</p> <br/>
<p style="color: red;">${error}</p> <br/>
<input type="button" value="View Books">
<input type="button" value="Home">
<form action="/ShoppingCartRemoving" method="post">
<input type="hidden" name="bookId" id="bookId"/>
</form>
</body>
</html>
This is the JSP code. I checked and realized that this never makes it to the servlet. But another JSP page that has the this same structure works fine. It's confusing. I'm trying to delete items from a shopping cart.
The JavaScript function is to get the bookId and put it in the hidden input field in form and then submit the form. This exact code worked fine in another JSP page.
I found the problem. It was the browser. Right after I changed my browser, It worked. The code is Fine and correct.
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[]");
i want to display a value in textbox based on selection of Combobox.. my code is below
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Account Open Page</title>
<script type="text/javascript">
function selectvalue(acct)
{
var savingamt=1000;
var currentamt=500;
var selectedText = acct.options[acct.selectedIndex].innerHTML;
var selectedValue = acct.value;
if (current) {
alert("Account Type is " + selectedText + " and " + selectedValue);
document.getElementById("depositamt").value = currentamt;
} else if (saving) {
alert("Account Type is " + selectedText + " and " + selectedValue);
document.getElementById("depositamt").value = savingamt;
}
}
</script>
</head>
<body>
<form name="frmAccount" action="com.bank.Handler.RegHandler" method="post">
<table>
<tr>
<td>Account Type</td>
<td>
<select name="cmbacttype" id="acct" onchange="selectvalue(this)">
<option value="">---Select Account Type---</option>
<option value="Deposit Amount Should be minimum 1000 Rupee" id="saving">Saving Account</option>
<option value="Deposit Amount Should be minimum 500 Rupee" id="current">Current Account</option>
</select>
</tr>
<tr>
<td>Deposit Amount</td>
<td><input type="text" name="deposit" id="depositamt"></td>
</tr>
<tr>
<td>Enter Amount</td>
<td><input type="text" name="amount" id="amount"></td>
</tr>
<tr>
<td>Total Amount</td>
<td><input type="text" name="totalamount" id="totalamount"></td>
</tr>
<tr>
<td><input type="submit" value="SUBMIT"></td>
</tr>
</table>
</form>
</body>
</html>
from the above code, on Selection of saving account 1000 value should get display on Deposit Amount textbox and on selection of current account it should display 500 value.
in javascript code , its displaying only the value of current , but if i select saving account it did not do anything... how can we display saving account value on selection of saving account option?
You are using the variable current inside your if condition. I do not know where you are getting the value of current. Looks like it is missing. If you add this line before accessing that in your if condition, It will work.
var current = selectedText==="Current Account";
if (current) {
}
else {
}
The expression selectedText==="Current Account" will return true or false based on the value of selectedText variable and you are good to use current in your if condition now.
Here is a working sample.
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" );
I have a Java EE web application using JSP pages. I included some JavaScript in JSP but it doesn't work when I run it on the server. It does work on Chrome.
Any ideas?
Here's my JSP page:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%# page isELIgnored="false" %>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" >
$(function(){ //Add, Save, Edit and Delete functions code
//$(".btnEdit").bind("click", Edit);
//$(".btnDelete").bind("click", Delete);
$("#btnAddd").bind("click", Add);
$('#btnSave1').click(function(event) {
var engagement_code = "a" ;//$('#code').val();
var engagement_name = "b";//$('#name').val();
//var harga = $('#harga').val();
var json = { "engagement_code" : engagement_code, "engagement_name" : engagement_name};
$.ajax({
url: 'engagementregister',
type: 'POST',
data: JSON.stringify({
'engagement_code': engagement_code,
'engagement_name': engagement_name,
}),
processData: false,
ContentType: 'application/json',
dataType: 'json',
success: function () {
console.log("success");}
});
});
});
//$("#btnSave1").bind("click", Save1);
function Add()
{ $("#list tbody").append(
"<tr>"+
"<td><img src='image/edit.png'/></td>"+
"<td><input id='code' type='text'/></td>"+
"<td><input id='name' type='text'/></td>"+
"<td><input type='text'/></td>"+
"<td><select id='sl'> <option value='ADM' label='ADM'/><option value='CSD' label='CSD'/><option value='PBS' label='PBS'/></select></td>"+
"<td><input type='text'/></td>"+
"<td><input type='text'/></td>"+
//"<td><img src='image/edit.png' class='btnSave'></td>"+
"<td><input type='button' value='Save' onclick='Save()' class='btnSave'/></td>" +"</tr>");
$(".btnSave").bind("click", Save);
//$(".btnEdit").bind("click", Edit);
};
function Save()
{
var par = $(this).parent().parent(); //tr
var tdCode = par.children("td:nth-child(2)");
var tdName = par.children("td:nth-child(3)");
var tdClient = par.children("td:nth-child(4)");
var tdSL = par.children("td:nth-child(5)");
var tdBU = par.children("td:nth-child(6)");
var tdEM = par.children("td:nth-child(7)");
var tdButton1 = par.children("td:nth-child(1)");
var tdButton2 = par.children("td:nth-child(8)");
//var e = document.getElementById("sl");
//var tdSL = e.options[e.selectedIndex].value;
tdCode.html(tdCode.children("input[type=text]").val());
tdName.html(tdName.children("input[type=text]").val());
tdClient.html(tdClient.children("input[type=text]").val());
tdSL.html(tdSL.children('select').val());
tdBU.html(tdBU.children("input[type=text]").val());
tdEM.html(tdEM.children("input[type=text]").val());
tdButton1.html("<img src='image/edit.png' class='btnEdit'/>");
//$(".btnEdit").bind("click", Edit);
};
</script>
<title>Engagement list</title>
</head>
<body>
<h1>Engagement list</h1>
<c:url var="editImgUrl" value="edit.png" />
<c:url var="deleteImgUrl" value="delete.png" />
<c:if test="${!empty list}">
<form>
<div style="overflow:scroll;overflow:auto">
<table id="list" style="border: 1px solid; width: 100%; text-align:center">
<thead style="background:#d3dce3">
<tr>
<th colspan="1"></th>
<th>Engagement code</th>
<th>Engagement Name</th>
<th>Client</th>
<th>SL</th>
<th>BU</th>
<th>EM</th>
<th colspan="1"></th>
</tr>
</thead>
<tbody style="background:#ccc">
<c:forEach items="${list}" var="eng">
<c:url var="detailsUrl" value="/details?id=${eng.engagement_code}" />
<tr>
<td><img src="${deleteImgUrl}"></img></td>
<td>${eng.engagement_code}</td>
<td><c:out value="${eng.engagement_name}" /></td>
<td><c:out value="${eng.client}" /></td>
<td><c:out value="${eng.SL}" /></td>
<td><c:out value="${eng.BU}" /></td>
<td><c:out value="${eng.EM}" /></td>
<td><img src="${editImgUrl}"></img></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</form>
</c:if>
<c:if test="${empty list}">
No records found.
</c:if>
<br/><br/><br/><br/><br/><br/><br/><br/>
<button id="btnAddd">New</button>
<button id="btnSave1">Save</button>
<%-- <input type="button" value="Save" onclick="Save1()"/>--%>
return
</body>
</html>
The eclipse internal browser is not a complete browser and it does not support all modern browsers features (JS, CSS ...)
You can start tomcat in eclipse and use other browser.