How to access gridview cell value with javascript - 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;
}

Related

How to interfere to the ASPxListBox both javascript and codebehind

When I click the update button, aspxlistbox is filled by codebehind. When I print firm code to AspxTextbox4, the firm code of the firm name is displayed in the second aspxtextbox. In order to do that, I use the lostfocus event of AspxTextbox4.
However, aspxlistbox resets all data. This is an unexpected issue for me. How can I cope with that?
This is my Asp code.
<dx:ASPxTextBox ID="ASPxTextBox4" runat="server" Width="100%"
ClientInstanceName="textbox_firmcode" AutoPostBack="false" EnableClientSideAPI="true">
<ClientSideEvents LostFocus="getFirmName" />
</dx:ASPxTextBox>
<dx:ASPxButton ID="ASPxButton4" runat="server" Text="Add" Width="100%" AutoPostBack="False">
<ClientSideEvents Click="addListClick" />
</dx:ASPxButton>
<dx:ASPxListBox ID="ASPxListBox1" runat="server" Width="100%" ClientInstanceName="ASPxListBox1"> </dx:ASPxListBox>
This is the Javascript code below.
function getFirmName(s, e) {
devpopup.PerformCallback('firmtxt|' + s.GetText());
}
function addListClick(s, e) {
var firmcode = textbox_firmcode.GetText();
var firmname = textbox_firmname.GetText();
var st = 0;
for (var i = 0; i < ASPxListBox1.GetItemCount() ; i++) {
var item = ASPxListBox1.GetItem(i);
if (item.value.split(' ')[0] == firmcode) st = 1;
}
if (st == 0) {
ASPxListBox1.BeginUpdate();
ASPxListBox1.AddItem(firmcode + ' ' + firmname);
ASPxListBox1.EndUpdate();
listcount++;
}
return false;
}
The last one is the codebehind C#
protected void devpopup_WindowCallback(object source, PopupWindowCallbackArgs e)
{
string[] data = e.Parameter.Split('|');
if(data[0].Equals("firmtxt"))
{
ASPxPageControl page = (ASPxPageControl)((ASPxPopupControl)source).FindControl("ASPxPageControl1");
ASPxRoundPanel rpanel = (ASPxRoundPanel)page.FindControl("ASPxRoundPanel2");
ASPxTextBox txtbox = (ASPxTextBox)rpanel.FindControl("ASPxTextBox5");
ASPxRoundPanel otherpanel = (ASPxRoundPanel)page.FindControl("ASPxRoundPanel2");
ASPxListBox firmlistbox = (ASPxListBox)otherpanel.FindControl("ASPxListBox1");
SFADatabase db = new SFADatabase(Server);
string[] frmname = db.getData("SFA_FIRM", new string[] { "FRMNAME" }, "WHERE FRMCODE='" + data[1] + "'");
if (frmname.Length > 0)
{
txtbox.Text = frmname[0];
txtbox.Focus();
//txtbox.Enabled = false;
}
else
{
//txtbox.Enabled = true;
txtbox.Text = "";
txtbox.Focus();
}
}
}
public void putUpdateData(string parameter, object source)
{
// Load the firm name to the listbox with update button
columns = new string[] { "FRMCODE", "FRMNAME" };
data = db.getData(SFADatabase.TABLE_FIRM, columns, "WHERE UGRREF=" + group_id + "");
// firmlistbox.Items.Clear();
firmcodelist.Clear();
firmnamelist.Clear();
for (int i = 0; i < SFADatabase.row_count; i++)
{
ListEditItem item = new ListEditItem(data[i * 2] + " " + data[i * 2 + 1], data[i * 2]);
firmlistbox.Items.Insert(i, item);
firmcodelist.Add(data[i * 2]);
firmnamelist.Add(data[i * 2 + 1]);
}
}
I have attached a gif to be more clear.
enter image description here

JavaScript, get dynamically created label's id

The label that is beings created holds a guid that I need later. I need to grab that information after the list of labels are created. Here's my code:
<button onclick="getAllListings()">Get All Listings Information</button>
<br />
<div id="divDataInsert" name="divDataInsert">
#foreach (MVCTest1.Models.Listing foundListings in Model._listings)
{
string pk_listing_id = "listingsid_" + foundListings.PK_Listings_ID;
string addressPK = "address_" + foundListings.PK_Listings_ID;
string address = foundListings.Address.ToString();
string cityPK = "city_" + foundListings.PK_Listings_ID;
string city = foundListings.City.ToString();
string statePK = "state_" + foundListings.PK_Listings_ID;
string state = foundListings.State.ToString();
string zipcodePK = "zipcode_" + foundListings.PK_Listings_ID;
string zipcode = foundListings.ZipCode.ToString();
string fullAddress = address + ", " + city + " " + state;
if (foundListings.PK_Listings_ID != null)
{
<input type="text" id="lblListing_#pk_listing_id" value="#pk_listing_id" />
}
}
</div>
function getAllListings(){
//var listingArray = [document.getElementById("lblListing_")];
for (var i = 0; i < [document.getElementById("lblListing_")].length; i++) {
var listingString = document.getElementById("lblListing_").value;
var guid = listingString.split("_");
alert(guid[1]);
i++;
}
}
My code behind
public ActionResult Index()
{
string sql = "SELECT TOP 10 [PK_Listings_ID], [Address], [City], [State], [ZipCode] FROM dbo.Listings";
ListingCollection ListOfListings = new ListingCollection();
ListOfListings._listings = new List<Listing>();
using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["MVCInsertData"].ToString()))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = sql;
using(SqlDataReader reader = cmd.ExecuteReader())
{
if (reader != null)
{
while (reader.Read())
{
Listing listing = new Listing();
listing.PK_Listings_ID = Convert.ToInt32(reader["PK_Listings_ID"]);
listing.Address = reader["Address"].ToString();
listing.City = reader["City"].ToString();
listing.State = reader["State"].ToString();
listing.ZipCode = reader["ZipCode"].ToString();
ListOfListings._listings.Add(listing);
}
}
}
}
conn.Close();
}
return View(ListOfListings);
}
one of the answers involved adding a JS array in the code behind. How do you do that?
*****Update*****
I have changed my input to this:
<input type="text" class="lblListing_" value="#pk_listing_id" />
And I have adjusted my JS to this:
function getAllListings(){
var listingsArray = document.getElementsByClassName("lblListing_");
for (var i = 0; i < listingsArray.length; i++) {
var listingString = listingsArray.value;
var guid = listingString.split("_");
alert(guid[1]);
}
}
Keep in mind, my JS is NOT inside a document.ready(). Should it be?
One way would be to have your code behind emit a JavaScript array of all labels. A different--and this is the approach I would take--would be to use a class name as a "tag". Emit:
<input type="text" class="lblListing_" ...>
Then in your fixed (not dynamic) JavaScript, you can do:
function getAllListings(){
var listings = document.getElementsByClassName("lblListing_");
for (var i = 0; i < listings.length; i++) {
var listingString = listings[i].value;
var guid = listingString.split("_");
alert(guid[1]);
}
}
Update for the follow-on question:
The JavaScript can be placed anywhere but will not run on load. When and how to run the function depends on what you need it to do. (I assume the alert is just to test the logic.)
You can easily achieve that with jQuery
$('someSelector').each(function() {
// do something
});
$("input[id^='lblListing_']").each(function() {
console.log($(this).val().split("_")[1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="lblListing_g-u-i-d-1" value="value1_g-u-i-d-1" />
<input type="text" id="lblListing_g-u-i-d-2" value="value2_g-u-i-d-2" />

No value is present in hidden field after page load

In the below code i have coded in page load.In this i have store regular expressions in hidRegExp.Value. Now i have to store this value in the hidden field.Now in javascript i have to validate the user input in textbox.But when i enter a value it shows blank alert.But i want to display the regular expression in alert.Pls help me to do this.
code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (FieldTypeInfo == FieldType.TextBox)
{
TblSearch.Visible = false;
TblDate.Visible = false;
tblDropd.Visible = false;
TblChk.Visible = false;
lblText.Text = FieldLabel;
//txtreq.Enabled = this.IsMandatory;
string strRegularExp = string.Empty;
if (ListOfRegularExpression != null)
{
for (int iRow = 0; iRow < ListOfRegularExpression.Count; iRow++)
{
strRegularExp += ListOfRegularExpression[iRow].ToString() + "~~";
hidRegExp.Value = strRegularExp;
if (iRow == ListOfRegularExpression.Count - 1)
{
strRegularExp = strRegularExp.TrimEnd("~~".ToCharArray());
txtField.Attributes.Add("onblur", "javascript:ValidateRegExp('" + txtField.ToString() + "');");
}
}
}
hidRegExp.Value = strRegularExp;
lbl.Text = "The value of the HiddenField control is " + hidRegExp.Value + ".";
}}
code:
<script type="text/javascript">
function ValidateRegExp(txtInput) {
var hiddenValue = document.getElementById("<%=hidRegExp.ClientID%>").value;
alert("hiddenValue" + hiddenValue+".");
var mySplitResult = new Array();
mySplitResult = hiddenValue.split("~~");
for (i = 0; i < mySplitResult.length; i++) {
//document.write("<br /> Array[" + i + " ]= " + mySplitResult[i]);
var re = new RegExp(mySplitResult[i]);
if (txtInput.match(re)) {
alert("Successful match");
} else {
alert("No match");
}
}
}
</script>
<asp:HiddenField ID="hidRegExp" runat="server" EnableViewState= "true" >
</asp:HiddenField >
<asp:Label ID="lbl" runat="server"></asp:Label>
Initially ListOfRegularExpression will be null so control will not enter into if (ListOfRegularExpression != null) and HiddenField.Value wont be set.
I have had the problem before. Honestly, I don't remember how I resolved it, but I tried a few things. Here they are:
For displaying the hidden field, add ClientIdMode as static on your hidden field like
<asp:HiddenField ID="hidRegExp" runat="server" EnableViewState="true" ClientIDMode="Static"></asp:HiddenField>
and in the JavaScript, use:
document.getElementById("hidRegExp");
If this does not work, try your approach with these below:
1) Try moving your hidden field before the script.
2) Try making it a label and use that in the JavaScript.
Hope this helps.

Add row in html table dynamically

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>

Get value from hidden field of ASP.Net in Javascript

<body onload="timer()">
<style type="text/css">
#time{
font-size:50pt;
}
#body
{
background-color:#F3F3F3;
}
</style>
<script type="text/javascript">
var digiclock = document.getElementById("<%= HiddenFieldMinutes.ClientID %>").value;
i = 0;
function timer() {
var digiformat = "";
if (i > 3599) {
var H = Math.floor(i / 3600);
}
else {
var H = 0;
}
var M = i - (H * 3600)
if (M > 59) {
M = Math.floor(M / 60)
}
else {
M = 0
}
var S = i - (M * 60)
if (H < 10) {
H = "0" + H;
}
if (M < 10) {
M = "0" + M;
}
if (S < 10) {
S = "0" + S;
}
document.getElementById('time').innerHTML = H + ":" + M + ":" + S;
setTimeout('timer()', 1000);
i++;
}
</script>
<table style="background-color:#F3F3F3;">
<tr>
<td><div><center><p style="font-family:Calibri;font-size:1.8em;color:#104E8B;">Total Elapsed Time</p> </center></div>
</td></tr>
<tr>
<td><div id="time"><center>90</center></div>
</td></tr>
<tr>
<td>
<center>
<form id="Form1" runat="server">
<asp:HiddenField ID="HiddenFieldMinutes" runat="server" Value="" />
<asp:Button ID="btnStop" runat="server" Text="Stop"
style="width:150px;height:30px;font-weight:bold;background-color:#104E8B;color:White;border:1px solid"
onclick="btnStop_Click" /></form></center>
<input id="HiddenTaskname" type="hidden" value="123" runat="server" />
</td></tr>
</table>
As you see above , i m trying to create a clock which starts from specified time provided by the user. I m storing the starting time period in the hidden field. The Code behind of this page load of this page is as follow:-
protected void Page_Load(object sender, EventArgs e)
{
HiddenFieldMinutes.Value = null;
if (! IsPostBack)
{
//Checking for any query string
if (Request["Code"] != null)
{
_elapsedNonProdTimeEntryID =Convert.ToInt32 (Request["Code"].ToString());
_starttime = _nonProduction.GetStartTimeOfActiveTImeEntryID(_elapsedNonProdTimeEntryID);
TimeSpan elapsedtimespan = System.DateTime.Now.Subtract(_starttime);
string hh = elapsedtimespan.Hours.ToString();
string mm = elapsedtimespan.Minutes.ToString();
string ss = elapsedtimespan.Seconds.ToString();
_differenceOfTimeSpan = hh + ":" + mm + ":" + ss;
HiddenFieldMinutes.Value = _differenceOfTimeSpan;
//ScriptManager.RegisterStartupScript(this, this.GetType(), "CloCkTImer", "javascript:timer(); ", true);
}
}
}
But when i m debugging i m getting error on this line .var digiclock = document.getElementById("<%= HiddenFieldMinutes.ClientID %>").value;
Please help me to improve this webpage and full fill my requirement.
The problem is in order of script and html elements. document.getElementById is called before html is rendered (DOM not ready yet). Just put script block after html.
I make one test which almost resembling your code,Just have a look here
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript" language="javascript">
function timer() {
alert(document.getElementById("<%= Hiddenfield1.ClientID %>").value);
}
</script>
</head>
<body onload="timer();">
<form id="form1" runat="server">
<div>
<asp:hiddenfield ID="Hiddenfield1" runat="server" value="static value"></asp:hiddenfield>
</div>
</form>
and here is CS code
protected void Page_Load(object sender, EventArgs e)
{
Hiddenfield1.Value = "dynamic value";
}
it give the Dynamic value as output.So it means your way of getting values is fine i think there is problem something else like you are trying to check hidden field value on postback or on another event if so then please take hidden field in update panel then you will get hidden field value otherwise you will remain getting the same error.
Hope it helps you.

Categories

Resources