ISSUE:
I am trying to generate a invoice in JSP. Where I am selecting values of item name from drop down. Drop down values are from database, On change of select tag I want to display the values associate to that item name from database(item price, HSN code, tax, description of item etc.). This is working for first row in table But when we are adding new row(by cloning row) we are unable perform on change function hence the related data is not displayed.
I have tried the below codes on my own. But couldn't get the desired result.
http://jsfiddle.net/leftstick/DVEXG/
http://www.iamrohit.in/add-remove-table-rows-dynamically/
https://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-append-and-remove-table-row-dynamically
http://jsfiddle.net/HjZkB/2/
http://jsfiddle.net/Dz24f/
https://youtu.be/KnKMGCSPj3Y
https://www.youtube.com/watch?v=FVSfp8yT8lA&feature=youtu.be
I added database connection to below code but did not gave me the desired result.
<%# page import = "java.sql.*"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Add / Remove Table Rows Dynamically</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
//$(function(){
$(document).ready(function () {
var j=1;
$("#table-data").on('click', 'input.addButton', function() {
var $tr = $(this).closest('tr');
var allTrs = $tr.closest('table').find('tr');
var lastTr = allTrs[allTrs.length-1];
var $clone = $(lastTr).clone();
$clone.find('td').each(function(){
var el = $(this).find(':first-child');
var r1= $(this).find(':first');
var idr= r1.attr('id') || null;
var id = el.attr('id') || null;
if(id) {
var i = id.substr(id.length-1);
var prefix = id.substr(0, (id.length-1));
el.attr('id', prefix+(+i+1));
el.attr('name', prefix+(+i+1));
}
});
$clone.find('input:text').val('');
$tr.closest('table').append($clone);
});
//var i=1;
$("#table-data").on('change', 'select', function(){
var value = $(this).val();
//var row1 = $(this).closest('table').find(' tbody tr:eq(0)').attr('id'); alert(row1);
var rid=$(this).closest('tr').attr("id"); alert(rid);
//var i=1;
$(this).closest('tr').find('input:text').each(function(){
$.get("myinvoice.jsp",{q:value},function(data){
//rid.val(data);
//$("#javaquery'"+i+"'").html(data);
//rid++;
$("#javaquery1").html(data);
$("#table-data option[value='"+value+"']").prop('selected', true);
});
}); //each
}); //select change
}); // ready function
//});
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0" id="table-data">
<thead>
<tr>
<td>SelectOne</td>
<td>TextBox</td>
<td>TextBox</td>
<td>Add</td>
</tr>
</thead>
<tbody>
<tr id="javaquery1">
<td>
<%
String desc = "";
String price= "";
// String q =request.getParameter("q"); System.out.println("q = "+q);
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","root1216");
Statement smt = con.createStatement(); //Create Statement to inte000ract
ResultSet r = smt.executeQuery("select item_name from item"); %>
<select name="Id.0" class="dropdn" id="Id.0" ><option value="">--Select--</option>
<%
while(r.next())
{%>
<option value="<%=r.getString("item_name")%>"> <%=r.getString("item_name")%> </option>
<% } %>
</select>
<br>
<%
Statement s=con.createStatement();
String q =request.getParameter("q"); System.out.println("q = "+q);
ResultSet r1=s.executeQuery("select * from item where(item_name='"+q+"');");
while (r1.next()) {
desc = r1.getString("item_description");
price=r1.getString("item_price"); System.out.println("price = "+price);
}
%>
</td>
<td><input type="text" id="Integer1.0" name="Integer1.0" value='<%= price %>'/></td>
<td><input type="text" id="Integer2.0" name="Integer2.0" value='<%= desc %>'/></td>
<td><input type="button" class="addButton" value="Add" /></td>
</tr>
</tbody>
<%
con.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>
enter image description here
enter image description here
How to shuffle and store each character of the string inside the table such that 1st letter of the pair is in random row position and 2nd letter of the pair is in random column position so that the 2 characters do not conflict in same row or column?
this is my code for creating a 7x7 grid
<table border="5px" cellspacing="30" align="center" class="table-bordered" style="color:#FFFFFF" width="400px" height="200px">
<% for(int row=1; row <= 7; row++) { %>
<tr>
<% for(int col=1; col<=7; col++) { %>
<td></td>
<% } %>
</tr>
<% } %>
</table>
And this is my code for shuffling of a string
<script>
function f1() {
var str = "abcdefghijklmnopqrstuvwxyz1234567890!##$%^&*()<>?";
var shuffled = str.split('').sort(function({
return0.2Math.random();
}).join('');
document.write(shuffled);
}
</script>
Now I want this shuffled string to get split up and get stored into each cell of the table.
Why are you troubling your jsp to do this? Let your scripting (jQuery) do this. In your HTML add id attribute to your table like this,
<div id="myDiv">
<table id="myTable" border="5px" cellspacing="30"
align="center" class="table-bordered" width="400px" height="200px">
<!-- Your content goes here -->
</table>
</div>
And in your scripting use the shuffled string you can create table like this,
$(document).ready(function() {
var myWord = "hello"; //Use any shuffled string
var length = myWord.length;
var createTable = '<tr>';
for ( var i=0; i < length; i++) { //Iterate through each character
if (myWord.charAt(i) != " ") {
// Create as table cell
createTable = createTable+'<td>'+myWord.charAt(i)+'</td>';
}
};
createTable = createTable+'</tr>';
$("#myTable").append(createTable);
});
Check the working sample.
Update :
Hope this is you're asking, how to find specific table definition.
$('#mytable tr').each(function() {
$(this).find("td:eq(0)").html("Your Shuffled Character maybe h"); // First cell
});
Requirements
Add value to a field in one html page.
Submit.
Should show the value on another html page.
Any update on first page should update the second page and not open a new one.
I have written some HTML which is below. What is happening is that once I press submit it opens another page (page2.html) in same window. What I want is to have two html windows and whenever I update Home page it should reflect on the same page. (page2.html)
Home.html
<code>
<html>
<form target="_blank" type=get action="page2.html">
<table>
<tr>
<td>OrderID:</td>
<td><input type=text name=orderId size=10></td>
</tr>
<tr>
<td colspan=2><input type=submit value="Submit"></td>
</tr>
</table>
</form>
</html>
page2.html
<code>
<html>
<script LANGUAGE="JavaScript">
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
firstname = unescape(params["orderId"]);
document.write("OrderID = " + firstname + "<br>");
</script>
</html>
Initialize params to an empty object instead of an array:
var params = {};
That will allow you to use strings and other values for a key.
Be sure you include var when declaring variables:
var params = getParams();
var firstName = unescape(params["orderId"]);
It's fine for learning, but try to never use document.write. It's better to use: https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild. In this case, you can add it to the body by doing:
var p = document.createElement("p");
p.innerHTML = "OrderID = " + firstname;
document.body.appendChild(p);
Other then that, your code looks fine. Please comment if you're still having issues. Use firebug or chrome's console to post any errors.
I could achieve this by adding a target="page2.html" in the home.html
So, I have a table in a jsp page which shows the data fetched from a database via an ArrayList forwarded to the page. Each row of the table has a radio button corressponding to it. Now, I would like to access the elements in the row (the ArrayList's members on the selection of the corresponding radio button and then click of an 'edit' button)
Any thoughts as to how to achieve this would be very much appreciated. Here's my code for a bit intro.
<%
ArrayList<requestbean> reqjsp = new ArrayList<requestbean>();
reqjsp = (ArrayList<requestbean>) (request.getAttribute("reqdb"));
%>
<script type ="text/javascript">
function x() {
var ele = document.getElementsByName('reqradio');
var i = ele.length;
for ( var j = 0; j < i; j++ ) {
if ( ele[j].checked ) {
document.getElementById("edireq").disabled = false;
alert('request ' + ( j + 1 ) + ' selected');
//Here is where the functionality is desired to access reqjsp.get(j)
}
}
}
</script>
<input type="button" name="edireq" id="edireq" onclick="x()" value="Edit Request">
These are a few columns in my table.
<%
for ( int i = 0; i < reqjsp.size(); i++ ) {
%>
<tr>
<td> <input type="radio" name="reqradio" id="req<%=(i+1) %>"></td>
<td><%= reqjsp.get(i).getRequestid() %></td>
<td><%= reqjsp.get(i).getRequestor() %></td>
<td><%= reqjsp.get(i).getApprover() %></td>
</tr>
<%} %>
You could generate a JavaScript array with JSP code and then access this generated variable in your JavaScript. But you would not be able to change anything in the underlying Java object this way:
<script type ="text/javascript">
<%
ArrayList<requestbean> reqjsp = new ArrayList<requestbean>();
reqjsp = (ArrayList<requestbean>) (request.getAttribute("reqdb"));
%>
var myJsArray = new Array();
<%
for ( int i = 0; i < reqjsp.size(); i++ ) {
%>
myJsArray.push('<%= reqjsp.get(i) %>');
<%
}
%>
// JavaScript code to access the myJsArray array
</script>
The JSP code will generate this kind of code:
<script type ="text/javascript">
var myJsArray = new Array();
myJsArray.push('value1');
myJsArray.push('value2');
myJsArray.push('value3');
// JavaScript code to access the myJsArray array
</script>
I want to get each cell value from an HTML table using JavaScript when pressing submit button.
How to get HTML table cell values?
To get the text from this cell-
<table>
<tr id="somerow">
<td>some text</td>
</tr>
</table>
You can use this -
var Row = document.getElementById("somerow");
var Cells = Row.getElementsByTagName("td");
alert(Cells[0].innerText);
function Vcount() {
var modify = document.getElementById("C_name1").value;
var oTable = document.getElementById('dataTable');
var i;
var rowLength = oTable.rows.length;
for (i = 1; i < rowLength; i++) {
var oCells = oTable.rows.item(i).cells;
if (modify == oCells[0].firstChild.data) {
document.getElementById("Error").innerHTML = " * duplicate value";
return false;
break;
}
}
var table = document.getElementById("someTableID");
var totalRows = document.getElementById("someTableID").rows.length;
var totalCol = 3; // enter the number of columns in the table minus 1 (first column is 0 not 1)
//To display all values
for (var x = 0; x <= totalRows; x++)
{
for (var y = 0; y <= totalCol; y++)
{
alert(table.rows[x].cells[y].innerHTML;
}
}
//To display a single cell value enter in the row number and column number under rows and cells below:
var firstCell = table.rows[0].cells[0].innerHTML;
alert(firstCell);
//Note: if you use <th> this will be row 0, so your data will start at row 1 col 0
You can also use the DOM way to obtain the cell value:
Cells[0].firstChild.data
Read more on that in my post at http://js-code.blogspot.com/2009/03/how-to-change-html-table-cell-value.html
You can get cell value with JS even when click on the cell:
.......................
<head>
<title>Search students by courses/professors</title>
<script type="text/javascript">
function ChangeColor(tableRow, highLight)
{
if (highLight){
tableRow.style.backgroundColor = '00CCCC';
}
else{
tableRow.style.backgroundColor = 'white';
}
}
function DoNav(theUrl)
{
document.location.href = theUrl;
}
</script>
</head>
<body>
<table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">
<% for (Course cs : courses){ %>
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">
<td name = "title" align = "center"><%= cs.getTitle() %></td>
</tr>
<%}%>
........................
</body>
I wrote the HTML table in JSP.
Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title.
courses is an ArrayList of Course objects.
The HTML table displays all the courses titles in each cell. So the table has 1 column only:
Course1
Course2
Course3
......
Taking aside:
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"
This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp . "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.
I told you just in case you'll want to use it because I searched a lot for it and I found questions like mine. But now I found out from teacher so I post where people asked.
The example is working.I've seen.
Just simply.. #sometime when larger table we can't add the id to each tr
<table>
<tr>
<td>some text</td>
<td>something</td>
</tr>
<tr>
<td>Hello</td>
<td>Hel</td>
</tr>
</table>
<script>
var cell = document.getElementsByTagName("td");
var i = 0;
while(cell[i] != undefined){
alert(cell[i].innerHTML); //do some alert for test
i++;
}//end while
</script>
<td class="virtualTd" onclick="putThis(this)">my td value </td>
function putThis(control) {
alert(control.innerText);
}
I found this as an easiest way to add row . The awesome thing about this is that it doesn't change the already present table contents even if it contains input elements .
row = `<tr><td><input type="text"></td></tr>`
$("#table_body tr:last").after(row) ;
Here #table_body is the id of the table body tag .
Here is perhaps the simplest way to obtain the value of a single cell.
document.querySelector("#table").children[0].children[r].children[c].innerText
where r is the row index and c is the column index
Therefore, to obtain all cell data and put it in a multi-dimensional array:
var tableData = [];
Array.from(document.querySelector("#table").children[0].children).forEach(function(tr){tableData.push(Array.from(tr.children).map(cell => cell.innerText))});
var cell = tableData[1][2];//2nd row, 3rd column
To access a specific cell's data in this multi-dimensional array, use the standard syntax: array[rowIndex][columnIndex].
Make a javascript function
function addSampleTextInInputBox(message) {
//set value in input box
document.getElementById('textInput').value = message + "";
//or show an alert
//window.alert(message);
}
Then simply call in your table row button click
<td class="center">
<a class="btn btn-success" onclick="addSampleTextInInputBox('<?php echo $row->message; ?>')" title="Add" data-toggle="tooltip" title="Add">
<span class="fa fa-plus"></span>
</a>
</td>