Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Capturing grid value with Javascript

Status
Not open for further replies.

Isadore

Technical User
Feb 3, 2002
2,167
US
Not finding a solution in a Tek-Tip Search I came up with a simple solution for capturing values form any row, column selected in a Datagrid using javascript. Microsoft recommends an x,y coordinate obj recognition routine but I found the dd list wouldn't behave. This solution is as follows:

The datagrid has a dropdownlist (id="ddOrder") with the following attribute added during the ItemDataBound event:
Code:
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then  
  ..
  CType(e.Item.FindControl("ddOrder"), DropDownList).attributes.add("OnChange","javascript:tabInvoice(this.value)")
  ..
End If

The dropdownlist occurs in the last column ([3]). A person selects a number (1-10) in the ddl and triggers the following javascript:

Code:
function tabInvoice(val){ 
var el = document.getElementById("dgOrders"); 
var ver = el.rows[val].cells[2].innerText;
text1.value = ver + ', ' + val;

In this way you capture the selected values from other columns using javascript. The orginal solution was found on Goggle Groups. Hopefully this post will pop-up in future searches. Any advantages/disadvantage might be noted.
 
Posted a minute too soon - this is not a final solution; will post back -- have to correct the column ct.
 
My purpose was to create a simple Order Form using a DataGrid and then supplment with javascript to carry out preliminary calculations on the client side. I was able to piece together several javascript routines and came up with the following.

The Demo can be seen here. Below is the single page ASPX-HTML page for anyone interested in reviewing the javascrpt.

If you run the routine locally be sure to adjust the default drodownlist name give by the local server (see below). The Access mdb can be downloaded here (7K) or you can create one from the SQL.

The code for aspx page is as follows. The Demo above shows the simple operations that are performed:
Code:
<%@ Page Language="VB" EnableViewState="false"%>
<%@Import Namespace = "Microsoft.VisualBasic"%>
<%@Import Namespace = "System"%>
<%@Import Namespace = "System.Web"%>
<%@Import Namespace = "System.Web.UI"%>
<%@Import Namespace = "System.Web.UI.WebControls"%>
<%@Import Namespace = "System.Web.UI.HtmlControls"%>
<%@Import Namespace = "System.Data"%>
<%@Import Namespace = "System.Data.OleDb"%>
<script runat="server">
 Dim i As Integer
 Dim cnnGrid As OleDbConnection = New OleDbConnection( _
  "Provider=Microsoft.Jet.OLEDB.4.0; " & _
  "Data Source=" & Server.MapPath("fpdb\OrdersGrid.mdb;"))
    Sub Page_Load(sender As Object, e As System.EventArgs) Handles MyBase.Load
       GetGrid()
     End Sub

     Sub GetGrid() 
       Dim cmdSelect As OleDbCommand = New OLEDbCommand("SELECT ProdID, CatNumber, ProdDescription, UnitCost FROM tblChemicals", cnnGrid)
     Try
       cnnGrid.Open()
       dgOrders.DataSource = cmdSelect.ExecuteReader()
       dgOrders.DataBind()       
       cnnGrid.Close()       
     Catch ex as System.Exception
       Message.Text = ex.ToString()
     Finally
        If (Not cnnGrid Is Nothing) Then
          cnnGrid.Close()
        End If
     End Try
    End Sub

    Sub btnClr_Click(sender as object, e As EventArgs)
      Session("CID") = txtID.Value
      Response.Redirect("ChemOrder.aspx")
    End Sub    

    Sub dgOrders_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.DataGridItemEventArgs)
       If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then       
         CType(e.Item.FindControl("ddOrder"), DropDownList).attributes.add("OnChange","javascript:getParent(this.value, this.parentNode.parentNode.rowIndex);")
         'Add the OnMouseOver and OnMouseOut method to the Row of DataGrid
         e.Item.Attributes.Add("onmouseover", "this.style.backgroundColor='#CCFFFF'")
         e.Item.Attributes.Add("onmouseout", "this.style.backgroundColor=''")
      End If
    End Sub
</script>
<script language="javascript" type="text/javascript">
var tmpObj; 
 function getParent(val, vix){   
  var currentElement = window.event.srcElement; 
    if(currentElement){ 
     findTR(currentElement); 
     var tbl = document.all("mytable"); 
      for(a = tbl.rows.length; a > 0; a--){ 
       tbl.deleteRow(a-1);                             
      } 
     //copy row..
     var tblRow = tbl.insertRow(); 
     var nCells = tmpObj.cells.length; 
     for(var b=0; b < nCells; b++){ 
      var tblCell = tblRow.insertCell(); 
      tblCell.innerHTML = tmpObj.cells[b].innerHTML; 
     }       
    }
    //populate cells..
    var pid = tbl.rows[0].cells[0].innerText;
    var pde = tbl.rows[0].cells[1].innerText;
    var vcs = tbl.rows[0].cells[2].innerText;
    var oelem=document.getElementById('row_1');
    //add table row..
    var otbody=oelem.parentNode;
    var orow=otbody.insertRow(oelem.sectionRowIndex+1);
    //add product description..
    var ocell2=orow.insertCell(orow.cells.length);
    ocell2.innerHTML=pde;
    ocell2.setAttribute("className", "desp");    
    //add delete button..
    var ocell2a=orow.insertCell(orow.cells.length);
    ocell2a.innerHTML='<input type='button' Value='X' class='cssbtn' runat=server onclick='deleteIt(this.parentNode.parentNode.rowIndex);'>'
    //add qty..
    var ocell3=orow.insertCell(orow.cells.length);
    ocell3.innerHTML= 'Ea.  ' + vcs;
    //add unit cost..
    var ocell4=orow.insertCell(orow.cells.length);
    ocell4.innerHTML= 'x  ' + '' + val + '&nbsp;&nbsp;&nbsp;';
    //Trim out $ sign..
    vcs = vcs.substr(1, vcs.length-1);
    //Calcule subtotal..
    var vprod = vcs*val;
    var ocell5=orow.insertCell(orow.cells.length);
    ocell5.innerHTML= '$&nbsp;' + vprod + '.00';
    //calc grand total..
    document.getElementById('mySpan').innerHTML=document.getElementById('mySpan').innerHTML*1+vprod + '.00';
    //add row id..
    var ocell6=orow.insertCell(orow.cells.length);
    ocell6.innerHTML = vix;
    ocell6.setAttribute("className", "hidcell");
  } 
function findTR(x){ 
 if(x.tagName == "TR"){ 
   tmpObj = x; 
   return 1;                               
 } 
 findTR(x.parentElement); 
 } 
function deleteIt(i) {
   var theTable = document.getElementById('invtable');
   var valc = theTable.rows[i].cells[4].innerText;
   var ocvix = theTable.rows[i].cells[5].innerText;
   ocvix = ocvix*1 + 2;
   theTable.deleteRow(i);
   //format html source name to two place holders..
   //localhost may change dollar sign to colon..
   if (ocvix > 9){
     var socv = 'dgOrders$ctl' + ocvix + '$ddOrder'
   }else{
     var socv = 'dgOrders$ctl0' + ocvix + '$ddOrder'
   }
   //adjust the total..
   var ocv = document.getElementById(socv);
   ocv.selectedIndex=0;
   //subtract from grand total..
   valc = valc.substr(1, valc.length-2);
   document.getElementById('mySpan').innerHTML=document.getElementById('mySpan').innerHTML*1-valc + '.00';
}
</script>
<style type="text/css">
body{overflow-x: auto;}
body{overflow-y: auto;}
.cssbtn{color: #FF0000;width:20px;}
.hidcell{text-align:left; color:#FFFFFF;}
.desp{color:#800000;background-color:#FFFFCC;}
</style>
<HTML>
<HEAD>
  <title>Chemical Order Form</title>
  <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="[URL unfurl="true"]http://schemas.microsoft.com/intellisense/ie5">[/URL]
</Head>
<body>
 <div align="center">
  <form id="frmOrder" runat="server">
     <font size="5" color="navy">Chemical Order Form</font>
      <Table border="0" cellspacing="0" cellpadding="2"><tr><td><img src="images/ghd.jpg"></td></tr>
      <tr><td>     
        <div style="height:249px;overflow:auto;width:520px;" align="center">         
        <asp:DataGrid id="dgOrders" runat="server" DataKeyField="ProdID" AutogenerateColumns="false" OnItemDataBound="dgOrders_ItemDataBound" align="center" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" showheader="false">
	<ItemStyle ForeColor="#330099" Font-Size="10"></ItemStyle>
	      <HeaderStyle Font-Size="10" horizontalalign="Center" verticalalign="Middle" ForeColor="#FFFFCC" BackColor="#990000"></HeaderStyle>
                  <Columns>
	              <asp:BoundColumn DataField="CatNumber" ItemStyle-HorizontalAlign ="center" ItemStyle-width="85px" HeaderText="Reference No."/>
                      <asp:BoundColumn DataField="ProdDescription" ItemStyle-HorizontalAlign ="center" HeaderText="Item Description"/>
                      <asp:BoundColumn DataField="UnitCost" runat="server" DataFormatString="{0:C}" HeaderText="Unit Cost" ItemStyle-width="60px" ItemStyle-HorizontalAlign ="center"/>
                      <asp:TemplateColumn HeaderText="Qty">
                        <ItemTemplate>
	                  <asp:DropDownList id="ddOrder" runat="server" >
                            <asp:ListItem Value=0>0</asp:ListItem>
                            <asp:ListItem Value=1>1</asp:ListItem>
                            <asp:ListItem Value=2>2</asp:ListItem>
                            <asp:ListItem Value=3>3</asp:ListItem>
                            <asp:ListItem Value=4>4</asp:ListItem>
                            <asp:ListItem Value=5>5</asp:ListItem>
                            <asp:ListItem Value=6>6</asp:ListItem>
                            <asp:ListItem Value=7>7</asp:ListItem>
                            <asp:ListItem Value=8>8</asp:ListItem>
                            <asp:ListItem Value=9>9</asp:ListItem>
                            <asp:ListItem Value=10>10</asp:ListItem>
                          </asp:DropDownList>
                        </ItemTemplate>
                      </asp:TemplateColumn>
                   </Columns>
	      </asp:DataGrid>
          </div> 
          </td></tr>
          <tr><td align="center">
          <TABLE name="invtable" id="invtable" border="0" width="510px" cellpadding="0" cellspacing="0" vspace="0"><tr id="row_1"></tr>
          <tr></td><td align="right" style="background-color:#970200;" colspan="7"><font color="#FFFF00">Total:&nbsp;&nbsp;$&nbsp;&nbsp;</font><font color="#00FFFF"><b><span id="myspan"></span></b></font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr></TABLE>
          </td></tr>          
          <tr><td align="center"><asp:Button id="btnClr" runat="server" Text="Clr" style="width:30px;color:#FF0000" onClick="btnClr_Click"/></td></tr>
          <tr><td> 
          <asp:Label id="Message" runat="server" Forecolor="red"/>
          <TABLE name="mytable" id="mytable" border="1" style="display:none;"><tr id="tr1" name="tr1"></tr></TABLE>
          <input type="hidden" id="txtID" runat="server" Value=43>
          </td></tr></Table>
      </form>
   </body>
 </div>
</HTML>
 
Looks and works well
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top