Add row in html table dynamically - javascript

I want to add row dinamically in my html table , then save the new row in my database with servlet.
how can i get the row in my servlet .please help me

<HTML>
<HEAD>
<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name="chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell3.appendChild(element2);
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
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>
</HEAD>
<BODY>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD><INPUT type="checkbox" name="chk"/></TD>
<TD> 1 </TD>
<TD> <INPUT type="text" /> </TD>
</TR>
</TABLE>
</BODY>

Try this code
<%#page import="javax.xml.crypto.Data"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*" %>
<%# page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<%Connection con =null; %>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test</title>
<%
//Connection con;
Statement s=null;
ResultSet rs=null;
String url = "";
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(url);
}
catch (ClassNotFoundException cnfex)
{
cnfex.printStackTrace();
}
String sql = "select * from tbPresicription";
try
{
s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs =s.executeQuery(sql);
while(rs.next())
{
// System.out.println("Name : "+rs.getString("PresicriptionIDP"));
}
System.out.println(" rs --> " + rs.first());
}
catch(Exception e)
{
System.out.println("Hello :"+e);
}
%>
<script src="js/jquery.js"></script>
<script type="text/javascript" language="javascript">
i=1;
a=1;
function addRow()
{
//Row Insert....
var table=document.getElementById("dataTable");
var row1=table.insertRow();
var row2=table.insertRow();
var row3=table.insertRow();
var row4=table.insertRow();
//Cell Insert Start
var cell1=row1.insertCell(0);
cell1.rowSpan="4";
cell1.innerHTML="";
cell1.align="center";
cell1.style.width = "30px";
cell1.innerHTML=i++;
//DropDownList
var cell1=row2.insertCell(0);
var abc=document.createElement("input");
abc.id="CompanyName"+a;
var Company=document.createElement("label");
Company.innerHTML =" Brand: ";
Company.style.width = "10px";
var Select = document.createElement('select');
var opt1 = document.createElement('option');
<% try
{
System.out.println(" rs --> click " + rs.first());
String IDP = null;
String Name=null;
%>
opt1.value="";
opt1.text="----Select Tablet----";
Select.appendChild(opt1);
<%
while (rs.next())
{
IDP = rs.getString("PresicriptionIDP")+":"+rs.getString("BrandName")+":"+rs.getString("Generic")+":"+rs.getString("Info")+":"+rs.getString("Dosage")+":"+rs.getString("Days")+":"+rs.getString("Qauntity")+":"+rs.getString("DosageInfo")+":"+rs.getString("TabletName")+":";
Name=rs.getString("TabletName");
// System.out.println("IDP :"+IDP+"Name is :"+Name);
%>
var opt2=document.createElement("option");
opt2.value="<%= IDP %>";
opt2.text="<%= Name %>";
Select.appendChild(opt2);
<%
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
Select.name="opt"+a;
Select.required="required";
Select.id="opt"+a;
var optid = "opt"+a;
var id=Select.id;
Select.setAttribute('onChange',"javascript:SelectItem(this.value,id);");
Select.style.width = "150px";
Company.readOnly = 'readonly';
cell1.appendChild(Select);
cell1.appendChild(Company);
cell1.appendChild(abc);
//Days Detail
var cell3=row2.insertCell(1);
var Days=document.createElement("input");
var Days1=document.createElement("label");
Days.type = "text";
Days1.innerHTML ="Days: ";
Days.name = "Days"+a;
Days.id="Days"+a;
Days.style.width = "30px";
cell3.rowSpan="2";
cell3.style.width = "83px";
cell3.appendChild(Days1);
cell3.appendChild(Days);
//Generic Detail
var cell1=row3.insertCell(0);
var Generic=document.createElement("input");
var Generic1 = document.createElement("label");
Generic.type = "text";
Generic1.innerHTML = "Generic: ";
Generic.name = "Generic"+a;
Generic.id = "Generic"+a;
Generic.style.width = "357px";
Generic.readOnly = 'readonly';
cell1.appendChild(Generic1);
cell1.appendChild(Generic);
//Dose Deside
var cell2=row2.insertCell(1);
var Dosage=document.createElement("input");
var Dosage1 = document.createElement("label");
Dosage.type = "text";
Dosage1.innerHTML = "Dosage: ";
Dosage.name = "Dosage"+a;
Dosage.id = "Dosage"+a;
Dosage.style.width = "80px";
cell2.rowSpan = "2";
cell2.appendChild(Dosage1);
cell2.appendChild(Dosage);
//Medicine Info
var cell1=row4.insertCell(0);
var Info=document.createElement("input");
var Info1 = document.createElement("label");
Info.type = "text";
Info1.innerHTML = "Info: ";
Info.name = "Info"+a;
Info.id = "Info"+a;
Info.readOnly = 'readonly';
Info.style.width = "500px";
cell1.style.width = "400px";
cell1.appendChild(Info1);
cell1.appendChild(Info);
cell1.colSpan="2";
//Medicine Dose Info...
var cell2 = row4.insertCell(1);
var DosageInfo = document.createElement("input");
var DosageInfo1 = document.createElement("label");
DosageInfo.type = "text";
DosageInfo1.innerHTML = "DosageInfo: ";
DosageInfo.name = "DosageInfo"+a;
DosageInfo.id = "DosageInfo"+a;
DosageInfo.style.width = "170px";
DosageInfo.readOnly = 'readonly';
cell2.colSpan = "2";
cell2.appendChild(DosageInfo1);
cell2.appendChild(DosageInfo);
//Medicine Qauntity define..
var cell4=row2.insertCell(3);
var Qauntity = document.createElement("input");
var Qauntity1 = document.createElement("label");
Qauntity.type = "text";
Qauntity1.innerHTML = "Qauntity: ";
Qauntity.name = "Qauntity"+a;
Qauntity.id = "Qauntity"+a;
Qauntity.style.width = "30px";
cell4.appendChild(Qauntity1);
cell4.appendChild(Qauntity);
cell4.rowSpan="2";
a++;
}
function SelectItem(val,id)
{
//alert('val : '+val);
var id1=id.substring(3);
//alert('id1 : '+id1);
var aa=val.split(":");
document.getElementById("CompanyName"+id1).value=aa[1];
document.getElementById("Generic"+id1).value=aa[2];
document.getElementById("Info"+id1).value=aa[3];
document.getElementById("Dosage"+id1).value=aa[4];
document.getElementById("Days"+id1).value=aa[5];
document.getElementById("Qauntity"+id1).value=aa[6];
document.getElementById("DosageInfo"+id1).value=aa[7];
}
function removeRow()
{
document.getElementById("dataTable").deleteRow(this);
}
</script>
<script type="text/javascript">
function addData()
{
//alert('hii : '+a);
var i;
var ss=0;
for(i=1;i<a;i++)
{
// alert('Hiiii : '+i);
var TabletName1=document.getElementById("opt"+i).value;
var CompanyName=document.getElementById("CompanyName"+i).value;
var Generic=document.getElementById("Generic"+i).value;
var Info=document.getElementById("Info"+i).value;
var Dosage=document.getElementById("Dosage"+i).value;
var Days=document.getElementById("Days"+i).value;
var Qauntity=document.getElementById("Qauntity"+i).value;
var DosageInfo=document.getElementById("DosageInfo"+i).value;
ss = ss+TabletName1;
}
// alert('TabletName1='+ss);
window.location.replace("index.jsp?name="+ss);
<%
int i=0;
String a = null;
try
{
String name=request.getParameter("name");
System.out.println("Name :"+name);
String data[]=name.split(":");
int size=data.length;
int size1=(size-1)/2;
String BrandName[]=new String[size1];
String TabletName[]=new String[size1];
String Generic[]=new String[size1];
String info[]=new String[size1];
String dosage[]=new String[size1];
String days[]=new String[size1];
String Qty[]=new String[size1];
String DosageInfo[]=new String[size1];
String PresicriptionIDP[]=new String[size1];
int x=0;
for(i=0;i<size+2;i++)
{
PresicriptionIDP[x]=data[i];
i++;
//System.out.println("PresicriptionIDP : "+PresicriptionIDP[x]);
BrandName[x]=data[i];
i++;
//System.out.println("BrandName : "+BrandName[x]);
Generic[x]=data[i];
i++;
//System.out.println("Generic : "+Generic[x]);
info[x]=data[i];
i++;
//System.out.println("info : "+info[x]);
dosage[x]=data[i];
i++;
//System.out.println("dosage : "+dosage[x]);
days[x]=data[i];
i++;
//System.out.println("days : "+days[x]);
Qty[x]=data[i];
i++;
//System.out.println("Qty :"+Qty[x]);
DosageInfo[x]=data[i];
i++;
//System.out.println("DosageInfo : "+DosageInfo[x]);
TabletName[x]=data[i];
i++;
//System.out.println("TabletName : "+TabletName[x]);
System.out.println("\n Value of : "+i);
x++;
System.out.println("Value of X="+x);
for(int ss=0;ss<x;ss++)
{
String insertTableSQL = "INSERT INTO tbPrescriptionNew"
+ "(PresicriptionIDP, TabletName, BrandName, Generic,Info,Dosage,Days,Qauntity,DosageInfo) VALUES"
+ "(?,?,?,?,?,?,?,?,?)";
PreparedStatement preparedStatement = con.prepareStatement(insertTableSQL);
preparedStatement.setString(1, PresicriptionIDP[ss]);
System.out.println("\n PresicriptionIDP" +PresicriptionIDP[ss]);
preparedStatement.setString(2, TabletName[ss]);
System.out.println("\n TabletName=" +TabletName[ss]);
preparedStatement.setString(3, BrandName[ss]);
System.out.println("\n BrandName=" +BrandName[ss]);
preparedStatement.setString(4, Generic[ss]);
System.out.println("\n Generic=" +Generic[ss]);
preparedStatement.setString(5, info[ss]);
System.out.println("\n info=" +info[ss]);
preparedStatement.setString(6, dosage[ss]);
System.out.println("\n dosage=" +dosage[ss]);
preparedStatement.setString(7, days[ss]);
System.out.println("\n days=" +days[ss]);
preparedStatement.setString(8, Qty[ss]);
System.out.println("\n Qty=" +Qty[ss]);
preparedStatement.setString(9, DosageInfo[ss]);
System.out.println("\n DosageInfo=" +DosageInfo[ss]);
// execute insert SQL stetement
preparedStatement.executeUpdate();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
}
</script>
</head>
<body>
<center>
<input type="button" class="selectItem" onClick="addRow('dataTable')" value = "AddRow">
<input type='button' value='Delete' onclick="removeRow()"/>
</center>
<table id="dataTable" border="1" width="894px;" align="center">
</table>
<input type="button" onClick="addData()" value = "AddData">
</body>
</html>

Related

How to save added data from HTML Table to SQL (PHPMYADMIN)

So here is my situation; I'm trying to save the data from the table which is added by filling up the form, I don't know how to save this to my database in phpmyadmin using javascript or ajax. A sample code is deeply appreciated. Thanks! PS: I'm a beginner, I'm just scraping the internet for code and trying to make do of what I get. Please Help :D
<html>
<body>
<div class = "inputfield">
<label>First Name:</label>
<input type="text" id="fname"><br>
<label>Last Name:</label>
<input type="text" id="lname"><br>
<label>Gender:</label>
<select name="gender" id="gender">
<option>Male</option>
<option>Female</option>
</select><br>
<label>HOURS:</label>
<input type="number" min=".5" max="12" step=".5" name="hours" id="hours" placeholder="--.5 to 12--"> <br>
</div>
<div class = "tablefield">
<table class="mtable" id="mtable">
<tr>
<th width="27%">First Name</th>
<th width="27%">Last Name</th>
<th width="15%">Gender</th>
<th width="15%">Hour</th>
<th width="16%">Edit</th>
</tr>
</table>
<table class="sumtable">
<tr><b>
<td class="sum">TOTAL HOURS</td>
<td class="sum1" id="sumtd"></td>
</b></tr>
</table>
</div>
<div class="buttons">
<button type = "button" onclick="add1('mtable')">ADD</button>
<button type = "reset" name="reset" class="btnclr">CLEAR</button>
<button type = "button" name="save" onclick="savefunc()">SAVE</button>
</div>
<input type = "hidden" name="hid1" id="hid1">
<input type = "hidden" name="hid2" id="hid2">
<input type = "hidden" name="hid3" id="hid3">
<input type = "hidden" name="hid4" id="hid4">
<script>
var sum = 0;
function add1(){
"use strict";
var hour1 = document.getElementById("hours").value;
sum = parseFloat(sum)+ parseFloat(hour1);
document.getElementById("sumtd").innerHTML = sum;
var table = document.getElementById("mtable"),rindex2;
var rowCount = table.rows.length;
var row = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
var td4 = document.createElement('td');
var element1 = document.createElement("Button");
element1.type = "button";
element1.name = "btnedit";
element1.innerHTML = "Update";
element1.setAttribute('class','btnedit');
var element2 = document.createElement("Button");
element2.type = "button";
element2.name = "btndel";
element2.innerHTML = "Delete";
element2.setAttribute('class','btndel');
for(var i=0; i<rowCount; i++) {
element1.onclick = function () {
try {
rindex2 = this.parentNode.rowIndex;
sum = parseFloat(sum) - parseFloat(table.rows[rindex2].cells[3].innerHTML);
console.log(rindex2);
this.parentNode.cells[0].innerHTML = document.getElementById("fname").value;
this.parentNode.cells[1].innerHTML = document.getElementById("lname").value;
this.parentNode.cells[2].innerHTML = document.getElementById("gender").value;
this.parentNode.cells[3].innerHTML = document.getElementById("hours").value;
sum = parseFloat(sum) + parseFloat(document.getElementById("hours").value);
document.getElementById("sumtd").innerHTML = sum;
}catch(e){
alert(e);
}};
element2.onclick = function () {
try {
rindex2 = this.parentNode.rowIndex;
console.log(rindex2);
sum = parseFloat(sum) - parseFloat(table.rows[rindex2].cells[3].innerHTML);
document.getElementById("sumtd").innerHTML = sum;
table.deleteRow(rindex2);
}catch(e){
alert(e);
}};
}
td1.innerHTML = document.getElementById("fname").value;
td2.innerHTML = document.getElementById("lname").value;
td3.innerHTML = document.getElementById("gender").value;
td4.innerHTML = document.getElementById("hours").value;
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
row.appendChild(td4);
row.appendChild(element1);
row.appendChild(element2);
table.children[0].appendChild(row);
}
function savefunc(){
var table1 = document.getElementById("mtable");
var hid1 = document.getElementById("hid1").value;
var hid2 = document.getElementById("hid2").value;
var hid3 = document.getElementById("hid3").value;
var hid4 = document.getElementById("hid4").value;
for (var r = 1, n = table1.rows.length; r < n; r++){
var c0 = table1.rows[r].cells[0].innerHTML;
var c1 = table1.rows[r].cells[1].innerHTML;
var c2 = table1.rows[r].cells[2].innerHTML;
var c3 = table1.rows[r].cells[3].innerHTML;
var c4 = table1.rows[r].cells[4].innerHTML;
hid1 = c0;
hid2 = c1;
hid3 = c2;
hid4 = c3;
console.log(hid1);
console.log(hid2);
console.log(hid3);
console.log(hid4);
}
}
</script>
</body>
</html>
I've figure it out. i just include this on the bottom of my loop statement and added a save.php file. Use this as reference https://www.studentstutorial.com/ajax/insert-data
$.ajax({
url: "save.php",
type: "POST",
data: {
fname: hid1,
lname: hid2,
gender: hid3,
hour: hid4
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
alert("Save Successful!");
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});

use input type to print out the date in year-mm-dd

I have three inputs for the user with date, activity and time. In the date field when the page starts i want the day of the date printet out in the label like this for example: 2015-12-20 and the user can change it if she/he wants.. But i try to make something with a function but cant get it work.
Below is my code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="6.1.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<form>
Date: <input type="text" id="Datum" name="Date" value=DateTime()>
Activity: <input type="text" id="Activity" name="Activ">
Time: <input type="text" id="time" name="Time">
<input type="button" onclick="AddRow()" value="Lägg till data!">
</form>
<table id="myTable">
<tr>
<td>Datum</td>
<td>Aktivit</td>
<td>Tid</td>
<td>Klar?</td>
</tr>
</table>
<button id="buttonforsend" onclick="SendData()">Skicka grönmarkerad data! </button>
<script>
function DateTime() {
var s = document.getElementById("Datum");
s = "";
var myYear = new Date();
s += myYear.getFullYear() + "-";
s += (myYear.getMonth() + 1) + "-";
s += myYear.getDate();
return s;
}
function AddRow()
{
var $check = document.createElement("INPUT");
$check.setAttribute("type", "checkbox");
$check.setAttribute("checked", "true");
$check.setAttribute("class", "checks");
$check.addEventListener("click", toggleClass);
function toggleClass() {
if (this.checked == true) {
this.parentNode.parentNode.className = "Green";
} else {
this.parentNode.parentNode.className = "Red";
}
}
var date = document.getElementById("Datum");
var activity = document.getElementById("Activity");
var time = document.getElementById("time");
var table = document.getElementById("myTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = date.value;
row.insertCell(1).innerHTML = activity.value;
row.insertCell(2).innerHTML = time.value;
row.insertCell(3).appendChild($check).value;
}
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < 3; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < 4; j++) {
var td = document.createElement('TD');
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function CheckData() {
var $arr = [];
var tb = document.getElementById("myTable");
var checks = tb.querySelectorAll(".checks"),
chk, tr;
for (var i = 0; i < checks.length; i++) {
chk = checks[i];
if (chk.checked) {
tr = chk.closest ? chk.closest('tr') : chk.parentNode.parentNode;
$arr.push({
date: tr.cells[0].innerText,
activity: tr.cells[1].innerText,
time: tr.cells[2].innerText
});
}
}
return $arr;
}
function SendData()
{
var obj = {Data: CheckData()};
var jsonString = "jsonString=" + (JSON.stringify(obj));
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","JSON_H.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form- urlencoded");
xmlhttp.setRequestHeader("Content-Length", jsonString.length);
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState === 4 && (xmlhttp.status === 200)){
alert(xmlhttp.responseText);
}
};
xmlhttp.send(jsonString);
}
</script>
</body>
</html>
You need to call DateTime and insert it's value in the input field, setting value=DateTime() won't set the value. For ex:
document.getElementById("Datum").value=DateTime();
Complete Code:
function DateTime() {
var s = document.getElementById("Datum");
s = "";
var myYear = new Date();
s += myYear.getFullYear() + "-";
s += (myYear.getMonth() + 1) + "-";
s += myYear.getDate();
return s;
}
document.getElementById("Datum").value=DateTime(); // This will insert the value
<form>
Date: <input type="text" id="Datum" name="Date" value="">
Activity: <input type="text" id="Activity" name="Activ">
Time: <input type="text" id="time" name="Time">
<input type="button" onclick="AddRow()" value="Lägg till data!">
</form>

Creating a table using javascript while retaining the first cell row

I have a html and javascript program where in I want to upon new queue of data the table will get cleared empty while retaining the first cell row that contains the content names of the table. How can I make it possible Here is my
<script>
function showAdTool(option){
var readData = document.getElementById('readData');
var addData = document.getElementById('addData');
var editData = document.getElementById('editData');
var deleteData = document.getElementById('deleteData');
if(option == '0'){
readData.style.display = 'inline';
addData.style.display = 'none';
editData.style.display = 'none';
deleteData.style.display = 'none';
}else if (option == '1'){
readData.style.display = 'none';
addData.style.display = 'inline';
editData.style.display = 'none';
deleteData.style.display = 'none';
}else if (option == '2'){
readData.style.display = 'none';
addData.style.display = 'none';
editData.style.display = 'inline';
deleteData.style.display = 'none';
}else{
readData.style.display = 'none';
addData.style.display = 'none';
editData.style.display = 'none';
deleteData.style.display = 'inline';
}
}
function dbOutputSelect(){
var option = document.getElementById('dbselector');
var dbvalue = document.getElementById('dbvalue');
if (option.value == '0'){
dbvalue.style.display = 'none';
}
else if (option.value == '1'){
dbvalue.style.display = 'inline';
}else if (option.value == '2'){
dbvalue.style.display = 'inline';
}else if (option.value == '3'){
dbvalue.style.display = 'inline';
}else if (option.value == '4'){
dbvalue.style.display = 'inline';
}else{
dbvalue.style.display = 'inline';
}
}
function ajaxRequest(){
clearTables();
var option = document.getElementById('dbselector').value;
var content = document.getElementById('contentholder').value;
var date = new Date();
var request= (date.getMonth()+1) + (date.getFullYear()) + (date.getHours()) + (date.getMinutes()) + (date.getSeconds()) + parseInt(((Math.random()*1000000)));
var url = './designIncludes/phpLogicIncludes/showdbcontent.php?option='+ option + '&content=' + content + '&request=' + request ;
downloadUrl(url,function(data){
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++){
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var info = markerNodes[i].getAttribute("info");
var budget = markerNodes[i].getAttribute("budget");
var tts = markerNodes[i].getAttribute("tts");
var type = markerNodes[i].getAttribute("type");
createTables(i,name,address,info,budget,tts,type);
}
});
}
function clearTables(){
}
function createTables(i,name,address,info,budget,tts,type){
var table = document.getElementById('tableDataContent');
var row = table.insertRow(-1);
var idCell = row.insertCell(0);
var nameCell = row.insertCell(1);
var addCell = row.insertCell(2);
var infoCell = row.insertCell(3);
var budgetCell = row.insertCell(4);
var ttsCell = row.insertCell(5);
var typeCell = row.insertCell(6);
idCell.innerHTML = i;
nameCell.innerHTML = name;
addCell.innerHTML = address;
infoCell.innerHTML = info;
budgetCell.innerHTML = budget;
ttsCell.innerHTML = tts;
typeCell.innerHTML = type;
}
function downloadUrl(url, callback){
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback (request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject){
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
}else if (window.DOMParser){
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
</script>
and here is my
<!DOCTYPE html>
<html lang="en">
<head>
<body>
<div id="MainContent">
</div>
<hr>
<div id="adminPanel">
<p>Administrator Tools:</p>
<p>Read Database Content | Add Data | Edit Data | Delete Data</p>
<div id="adminPanelContent">
<div id="readData">
<form>
Show Database data by: <select id="dbselector" onchange = "dbOutputSelect();">
<option value = '0'>All Data</option>
<option value = '1'>By Name</option>
<option value = '2'>By Address</option>
<option value = '3'>Budget</option>
<option value = '4'>Time to spend</option>
<option value = '5'>Marker Type</option>
</select>
<p id="dbvalue" style="display:none;"> Content: <input type="text" size="16" id="contentholder"></p>
<input type="button" value="Submit" onclick="ajaxRequest();">
</form>
<div id="tableData">
<table id="tableDataContent" border="1" widht="100%">
<tr><td>Id No.</td><td>Name</td><td>Address</td><td>Information</td><td>Budget</td><td>Time to Spend</td><td>Site Type</td></tr>
</table>
</div>
</div>
<div id="addData">Mysel</div>
<div id="editData">Myse</div>
<div id="deleteData">Mys</div>
</div>
</div>
</div>
</div>
</body>
</html>
On my table I want to retain the original table content such as Id, name, adress information etc. in my HTML page.
I would recommend using thead and tbody elements in your table.
MDN link
Then you only have to add data to the tbody, and clear the data in the tbody
<table id="tableDataContent">
<thead>
<tr>
<th>Id No.</th>
<th>Name</th>
<th>Address</th>
<th>Information</th>
<th>Budget</th>
<th>Time to Spend</th>
<th>Site Type</th>
</tr>
</thead>
<tbody>
<!-- Table Data -->
</tbody>
</table>
Try something like this:
while(table.rows.length > 1){
table.rows[1].parentElement.removeChild(table.rows[1]);
}

Javascript: fetch values from textbox of a dynamic datagrid. (skipping some textboxes)

i have seen similar questions to this but none can assist me.as my code is missing some results and i don't now why.
as seen on the image above the output is 6 results instead of 12
This is the code am using to get the values
//Fetch Sales**********************************************
function fetchsales(){
var Dt = document.getElementById("sDate").value;
var Usr = document.getElementById("UserID").value;
var Stp = document.getElementById("tstamp").value;
var e = document.getElementById("sdepot");
var Dpt = e.options[e.selectedIndex].value;
var sale = new Array();
var Tbl = document.getElementById('tbl_sales'); //html table
var tbody = Tbl.tBodies[0]; // Optional, based on what is rendered
for (var i = 2; i < tbody.rows.length; i++) {
var row = tbody.rows[i];
for (var j = 2; j < row.cells.length; j++) {
var cell = row.cells[j];
// For Every Cell get the textbox value
var unitsold = cell.childNodes[0].value ;
//Get selectbox distributor
var Sdist = row.cells[1].childNodes[0]; //Select box always on second coloumn
var Distributor = Sdist.options[Sdist.selectedIndex].value;
//Get selectbox Product
var Sprod = tbody.rows[1].cells[j].childNodes[0];
var Product = Sprod.options[Sprod.selectedIndex].value;
sale[(j*i)] = new Array ('('+Dt,Dpt,Product,unitsold,Distributor,Usr,Stp+')<br/>');
}
}
//Debug
var fsale = new Array();
fsale = sale.filter(function(n){return n});
document.getElementById("output").innerHTML = fsale;
}
//End Fetch Sales******************************************************
And this is the Whole Document with the Above code included.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
</style>
<script type="text/javascript">
//*********************************Start Add Row **********************************************************
function addRowToTable() {
var tbl = document.getElementById('tbl_sales'); //html table
var columnCount = tbl.rows[0].cells.length; //no. of columns in table
var rowCount = tbl.rows.length; //no. of rows in table
var row = tbl.insertRow(rowCount); //insert a row method
// For Every Row Added a Checkbox on first cell--------------------------------------
var cell_1 = row.insertCell(0); //Create a new cell
var element_1 = document.createElement("input"); //create a new element
element_1.type = "checkbox"; //set element type
element_1.setAttribute('id', 'newCheckbox'); //set id attribute
cell_1.appendChild(element_1); //Append element to created cell
// For Every Row Added add a Select box on Second cell------------------------------
var cell_2 = row.insertCell(1);
var element_2 = document.createElement('select');
element_2.name = 'SelDist' + rowCount;
element_2.className = 'styled-select';
element_2.options[0] = new Option('John Doe', '1');
element_2.options[1] = new Option('Dane Doe', '2');
cell_2.appendChild(element_2);
// For Every Row Added add a textbox on the rest of the cells starting with the 3rd,4th,5th... coloumns going on...
if (columnCount >= 2) { //Add cells for more than 2 columns
for (var i = 3; i <= columnCount; i++) {
var newCel = row.insertCell(i - 1); //create a new cell
var element_3 = document.createElement("input");
element_3.type = "text";
element_3.className = "rounded";
element_3.name = 'txt_r'+ rowCount +'c'+(i-1);
element_3.id = 'txt_r'+ rowCount +'c'+(i-1);
element_3.size = 5;
element_3.value = 'txt_r'+rowCount+'c'+(i-1);
newCel.appendChild(element_3);
}
}
}
//***************************** End Add Row ***************************************************************
// *****************************Start Add Column**********************************************************
function addColumn() {
var tblBodyObj = document.getElementById('tbl_sales').tBodies[0];
var rowCount = tblBodyObj.rows.length;
//for every Coloumn Added Add checkbox on first row ----------------------------------------------
var newchkbxcell = tblBodyObj.rows[0].insertCell(-1);
var element_4 = document.createElement("input");
element_4.type = "checkbox";
element_4.setAttribute('id', 'newCheckbox');
newchkbxcell.appendChild(element_4);
//For Every Coloumn Added add Drop down list on second row-------------------------------------
var newselectboxcell = tblBodyObj.rows[1].insertCell(-1);
var element_5 = document.createElement('select');
element_5.name = 'SelProd' + rowCount;
element_5.className = 'styled-select';
element_5.options[0] = new Option('Product11', '11');
element_5.options[1] = new Option('Product12', '12');
element_5.options[2] = new Option('Product13', '13');
element_5.options[3] = new Option('Product14', '14');
element_5.options[4] = new Option('Product15', '15');
element_5.options[5] = new Option('Product16', '16');
newselectboxcell.appendChild(element_5);
// For Every Coloumn Added add a textbox on the rest of the row cells starting with the 3rd,4th,5th......
for (var i = 2; i < tblBodyObj.rows.length; i++) { //Add cells in all rows starting with 3rd row
var newCell = tblBodyObj.rows[i].insertCell(-1); //create new cell
var ClmCount = ((tblBodyObj.rows[0].cells.length)-1);
var element_6 = document.createElement("input");
element_6.type = "text";
element_6.className = "rounded"
element_6.name = 'txt_r'+ i + 'c' + ClmCount;
element_6.id = 'txt_r'+ i + 'c' + ClmCount;
element_6.size = 5;
element_6.value = 'txt_r'+i+'c'+ClmCount;
newCell.appendChild(element_6)
}
}
//*****************************Start Delete Selected Rows **************************************************
function deleteSelectedRows() {
var tb = document.getElementById('tbl_sales');
var NoOfrows = tb.rows.length;
for (var i = 0; i < NoOfrows; i++) {
var row = tb.rows[i];
var chkbox = row.cells[0].childNodes[0]; //get check box object
if (null != chkbox && true == chkbox.checked) { //wheather check box is selected
tb.deleteRow(i); //delete the selected row
NoOfrows--; //decrease rowcount by 1
i--;
}
}
}
//*****************************End Delete Selected Columns **************************************************
//*****************************Start Delete Selected Columns ************************************************
function deleteSelectedColoumns() {
var tb = document.getElementById('tbl_sales'); //html table
var NoOfcolumns = tb.rows[0].cells.length; //no. of columns in table
for (var clm = 3; clm < NoOfcolumns; clm++) {
var rw = tb.rows[0]; //0th row with checkboxes
var chkbox = rw.cells[clm].childNodes[0];
console.log('Current Coloumn:'+clm+',', NoOfcolumns, chkbox); // test with Ctrl+Shift+K or F12
if (null != chkbox && true == chkbox.checked) {
//-----------------------------------------------------
var lastrow = tb.rows;
for (var x = 0; x < lastrow.length; x++) {
tb.rows[x].deleteCell(clm);
}
//-----------------------------------------
NoOfcolumns--;
clm--;
} else {
//alert("not selected");
}
}
}
//*****************************End Delete Selected Columns **************************************************
//Fetch Sales**********************************************
function fetchsales(){
var Dt = document.getElementById("sDate").value;
var Usr = document.getElementById("UserID").value;
var Stp = document.getElementById("tstamp").value;
var e = document.getElementById("sdepot");
var Dpt = e.options[e.selectedIndex].value;
var sale = new Array();
var Tbl = document.getElementById('tbl_sales'); //html table
var tbody = Tbl.tBodies[0]; // Optional, based on what is rendered
for (var i = 2; i < tbody.rows.length; i++) {
var row = tbody.rows[i];
for (var j = 2; j < row.cells.length; j++) {
var cell = row.cells[j];
// For Every Cell get the textbox value
var unitsold = cell.childNodes[0].value ;
//Get selectbox distributor
var Sdist = row.cells[1].childNodes[0]; //Select box always on second coloumn
var Distributor = Sdist.options[Sdist.selectedIndex].value;
//Get selectbox Product
var Sprod = tbody.rows[1].cells[j].childNodes[0];
var Product = Sprod.options[Sprod.selectedIndex].value;
sale[(j*i)] = new Array ('('+Dt,Dpt,Product,unitsold,Distributor,Usr,Stp+')<br/>');
}
}
//Debug
var fsale = new Array();
fsale = sale.filter(function(n){return n});
document.getElementById("output").innerHTML = fsale;
}
//End Fetch Sales******************************************************
//on loading create 3 coloumns and 2 rows
window.onload = function () {addColumn();addColumn();addColumn();addRowToTable();addRowToTable();};
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Distributor Sales</title>
</head>
<body>
<!--A--->
<div class="datagrid shadow" style="float:left; min-width:160px; width:220px">
<table id="top">
<tbody>
<tr>
<td width="100px">
<label for="textfield2">Date</label>
<input id="sDate" name="sDate" type="date" size="10" class="rounded" value="2013-06-04" />
</td>
</tr>
<tr class="alt">
<td width="220px">
<label for="select">Depot</label>
<select name="sdepot" id="sdepot" class="styled-select">
<option value="1">Muranga</option>
<option value="2" selected="selected">Nyahururu</option>
<option value="3">Karatina</option>
</select>
</td>
</tr>
</tbody>
</table>
</div>
<!--C--->
<div class="datagrid shadow" style="float:left; margin-left:20px; width:250px; min-width:250px">
<table>
<tbody>
<tr>
<td>
<label for="textfield4">User ID</label>
<input id="UserID" name="UserID" type="text" class="rounded" value="121" />
</td>
</tr>
<tr class="alt">
<td>
<label for="textfield5">Time Stamp</label>
<input type="date" name="tstamp" id="tstamp" class="rounded" value="2013-06-02" />
</td>
</tr>
</tbody>
</table>
</div>
<div style="clear:both"></div>
</br>
<div class="mainG gradient-style shadow" style="min-width:500px; min-height:120px">
<table id="tbl_sales" border="1" bordercolor="#E1EEF4" background="table-images/blurry.jpg">
<tr>
<td></td>
<td><input type="button" name="button3" id="button3" value="-Row" onclick="deleteSelectedRows()" />
<input type="button" name="button4" id="button4" value="-Coloumn" onclick="deleteSelectedColoumns()" /></td>
</tr>
<tr>
<td></td>
<td><input type="button" name="addrowbutton" id="adrwbutton" value="+Row" onclick="addRowToTable();" />
<input type="button" name="adclmbutton" id="addclmnbutton" value="+Coloumn" onclick="addColumn()" />
</td>
</tr>
</table>
</div>
<div style="clear:both"></div>
<br/>
<div class="datagrid shadow" style="float:left; margin-left:20px; width:200px; min-width:200px; padding-left:10px">
<table id="bottom1" style="min-width:200px">
<tbody>
<tr>
<td>
<div align="center"><input name="myBtn" type="submit" value="Save Information" onClick="javascript:fetchsales();">
</td>
</tr>
</tbody>
</table>
</div>
<div style="clear:both"></div>
<br/>
<div id="output"></div>
</body>
</html>
NB: am hoping to concatenate the result to a mysql insert statement
Any assistance will be greatly appreciated.
The problem comes from this line:
sale[(j*i)] = new Array ('('+Dt,Dpt,Product,unitsold,Distributor,Usr,Stp+')<br/>');
using the for loops indexes multiplied by themselves doesnt ensure unique array indexes, in some cases they are repeated (like for example 2*3 and 3*2) and the previous value in the array gets overwritten.

How to access gridview cell value with javascript

I have a javascript function that I am trying to validate the inputs of a gridview. My problem is that I cannot get the value of the cell. Here is what I have:
function fcnCheck() {
var grid = document.getElementById("<%= GridViewProducts.ClientID %>");
var cellPivot;
if (grid.rows.length > 0) {
for (i = 1; i < grid.rows.length-1; i++) {
cellPivot = grid.rows[i].cells[0];
cellStatus = grid.rows[i].cells[1];
if (cellPivot == "Yes" and cellStatus == "") {
alert("You must select an answer for all columns if Pivot is yes")
return false;
}
}
}
}
This line does not work: cellPivot = grid.rows[i].cells[0];
Most likely you want (edit)
var theDropdown = grid.rows[i].cells[0].elements[0];
var selIndex = theDropdown.selectedIndex;
cellPivot = theDropdown.options[selIndex].value;
Another possibly easier or more reliable way to do this would be to tag the cells controls you want in some way and select them directly?
http://aspdotnetcodebook.blogspot.com/2010/01/how-to-get-cell-value-of-gridview-using.html#comment-form
Code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var list = "";
$("#btnGet").click(function() {
$("#<%=GridView1.ClientID %> tr").each(function() {
//Skip first(header) row
if (!this.rowIndex) return;
var age = $(this).find("td:last").html();
list += age + "</br>";
});
$("#listAge").html(list)
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<input type="button" id="btnGet" value="Get Cell Value" />
<div id="listAge">
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Create Object of person class
Person personObject = new Person();
//Assign Person list to GridView
GridView1.DataSource = personObject.GetPersonList();
//Call Bindmethod of GridView
GridView1.DataBind();
}
}
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public List<Person> GetPersonList()
{
//Retrun List of Person
List<Person> list = new List<Person>()
{
new Person{ID=1,Name="Person1",Age=32},
new Person{ID=2,Name="Person2",Age=45},
new Person{ID=3,Name="Person3",Age=43},
new Person{ID=4,Name="Person4",Age=21},
new Person{ID=5,Name="Person5",Age=76},
new Person{ID=6,Name="Person6",Age=54},
};
return list;
}
}
<script language="javascript" type="text/javascript">
function Calculate()
<br/>
{
<br/>
var grid = document.getElementById("<%=GridID.ClientID%>");
<br/>
var sum = 0; <br/>
for (var i = 1; i < grid.rows.length; i++)<br/>
{ <br/>
var Cell = grid.rows[i].getElementsByTagName("input");
<br/>if (!Cell[4].value) {sum += 0; } else { sum += parseFloat(Cell[4].value);} }
<br/>
document.getElementById("<%=TextBox1.ClientID%>").value = sum;
}
<br/>
</script>
------------------------------------------------------------------------
<asp:TemplateField HeaderText="Current payment" >
<ItemTemplate>
<asp:TextBox ID="cridnvalue" runat="server" Width="70px" BorderStyle="None" onkeyup="CalculateTax();" ></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="120px" />
</asp:TemplateField>
//your gridview id in my case my gridview is named dgd and the id comes from
// ClientID
var myGrid = document.getElementById("<%= dgd.ClientID %>");
var oRows = myGrid.rows;
var k;
for (k = 1; k < oRows.length; k++)
{
var currentRow = myGrid.rows[k];
//now you can see the 1st,2nd and 3trd column value
alert(currentRow.cells[1].innerHTML);
alert(currentRow.cells[2].innerHTML);
alert(currentRow.cells[3].innerHTML);
}
function rowWisegetcellvalueingridview() {
///concat string
var str1 = "";
var n = document.getElementById('hdnColumn').value;
///concat string
var grid = document.getElementById('GridView1');
var Inputs = grid.getElementsByTagName('input');
var Inputsa = grid.getElementsByTagName('a');
var Inputsspan = grid.getElementsByTagName('span');
var Input = Inputs.length;
var j = 0;
var p = 0;
var r = 0;
for (t = 0; t < grid.rows.length - 1; t++) {
var HdnID1 = Inputs[j].value;
var HdnID2 = Inputs[j + 1].value;
var HdnID3 = Inputs[j + 2].value;
var HdnID4 = Inputs[j + 3].value;
var HdnID5 = Inputsa[p].innerHTML;
var HdnID6 = Inputsa[p + 1].innerHTML;
var HdnID7 = Inputsspan[r].innerHTML;
var varConcat = "(" + HdnID1 + "," + HdnID2 + "," + HdnID3 + "," + HdnID4 + "," + HdnID5 + "," + HdnID6 + "," + HdnID7 + "),\n";
n = n.concat(varConcat);
j = j + 4;
p = p + 2;
r = r + 1;
}
return false;
}

Categories

Resources