Gridview onmouseover details - javascript

I am trying to display more information about form in on mouse over. I have written code everything with the help of google still i am not able display Please let me know where i made mistake
my aspx code is
<div id="divGrid" style="width: auto; float: left">
<div>
<asp:GridView ID="gvEdit" runat="server" BorderStyle="Solid" BorderColor="lightblue" CssClass="grid" OnRowDataBound="gvEdit_RowDataBound" FooterStyle-CssClass="footer" GridLines="None" BorderWidth="2px" PagerSettings-Visible="true" ShowFooter="true" PagerSettings-Position="Top" AllowSorting="true" OnSorting="gvEdit_Sorting" ShowHeaderWhenEmpty="true" EmptyDataText="No Record found" AutoGenerateColumns="False" DataKeyNames="slno" OnRowCreated="gvEdit_RowCreated" OnDataBound="gvEdit_DataBound" OnPageIndexChanging="gvEdit_PageIndexChanging" Width="100%" AllowPaging="True" PageSize="50" OnRowCommand="gvEdit_RowCommand">
<HeaderStyle HorizontalAlign="Center" BackColor="#086A87" ForeColor="White" />
<FooterStyle BackColor="#086A87" />
<RowStyle BackColor="#ffffff" ForeColor="DarkBlue" />
<AlternatingRowStyle BackColor="#b3e5fc" ForeColor="DarkBlue" />
<PagerSettings Position="Top" />
<PagerStyle Height="65px" HorizontalAlign="Center" CssClass="pagecounthead" />
<PagerTemplate>
<table align="center" style="width: 100%;" class="pagecounthead" cellpadding="0" cellspacing="0" border="0">
<tr style="background-color: #fff">
<td align="left" style="text-align: left; font-weight: 600; font-size: 24px; width: 15%; padding-left: 0px">Form List</td>
<td align="center" style="width: 45%;">
<asp:Panel ID="pnelred" runat="server">
<table align="center" width="99%">
<tr>
<td style="background-color: #fff; text-align: right; padding-left: 0px">
<asp:ImageButton ToolTip="First Page" CommandName="Page" CommandArgument="First" runat="server" ID="ImgeBtnFirst" ImageUrl="../Images/First.jpg" />
</td>
<td style="background-color: #fff; text-align: right">
<asp:ImageButton ToolTip="Previous Page" CommandName="Page" CommandArgument="Prev" runat="server" ID="ImgbtnPrevious" ImageUrl="../Images/Previous.jpg" />
</td>
<td style="width: 25%; background-color: #fff; text-align: center">
<asp:Label ID="lblpageindx" CssClass="labelBold" Text="Page : " runat="server"></asp:Label>
<asp:DropDownList ToolTip="Goto Page" ID="ddlPageSelector" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlPageSelector_SelectedIndexChanged" CssClass="combo_common_nowidth hide">
</asp:DropDownList>
</td>
<td style="background-color: #fff; text-align: left">
<asp:ImageButton ToolTip="Next Page" CommandName="Page" CommandArgument="Next" runat="server" ID="ImgbtnNext" ImageUrl="../Images/Next.jpg" />
</td>
<td style="background-color: #fff; text-align: left">
<asp:ImageButton ToolTip="Last Page" CommandName="Page" CommandArgument="Last" runat="server" ID="ImgbtnLast" ImageUrl="../Images/Last.jpg" />
</td>
</tr>
</table>
</asp:Panel>
</td>
<td style="width: 40%; text-align: right; padding-right: 10px; padding-left: 0px">
<asp:Panel runat="server" ID="s" DefaultButton="Button1">
<asp:TextBox ID="txtsearch" runat="server" CssClass="txtbox" />
<asp:FilteredTextBoxExtender ID="fteCardHolderName" runat="server" TargetControlID="txtsearch"
FilterType="LowercaseLetters,UppercaseLetters,Numbers,Custom" ValidChars=" -">
</asp:FilteredTextBoxExtender>
<asp:Button ID="Button1" Text="Search" runat="server" CssClass="searchbtn pad" CommandName="s" />
<asp:Button ID="Button2" Text="Reset" runat="server" CssClass="resetbtn" OnClick="Reset_Click" />
</asp:Panel>
</td>
</tr>
</table>
</PagerTemplate>
<Columns>
<asp:BoundField DataField="form_key" HeaderText="FilingID" HeaderStyle-CssClass="hide" ItemStyle-CssClass="hide" FooterStyle-CssClass="hide" />
<asp:BoundField DataField="business_key" HeaderText="BusinessKey" HeaderStyle-CssClass="hide" ItemStyle-CssClass="hide" FooterStyle-CssClass="hide" />
<asp:BoundField DataField="ref_no" HeaderText="Reference" HeaderStyle-Width="11%" HeaderStyle-CssClass="borderright" SortExpression="ref_no" HeaderStyle-Font-Overline="false" />
<asp:BoundField DataField="fum" HeaderText="Period" HeaderStyle-Width="15%" HeaderStyle-CssClass="borderright" ItemStyle-Width="8%" SortExpression="fum" />
<asp:BoundField DataField="filing_type" HeaderText="Filing Type" HeaderStyle-CssClass="borderright" HeaderStyle-Width="10%" SortExpression="filing_type" />
<asp:BoundField DataField="business_name" HeaderText="Business" HeaderStyle-CssClass="borderright" HeaderStyle-Width="16%" />
<asp:BoundField DataField="filing_status" HeaderText="Status" HeaderStyle-CssClass="borderright" HeaderStyle-Width="11%" SortExpression="filing_status" />
<asp:TemplateField HeaderStyle-Width="7%" HeaderStyle-CssClass="borderright" HeaderText="View">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="lnkBtnViewDetails_Click" Text='<%#Eval("form_details")%>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="10%" HeaderStyle-CssClass="nopad" FooterText="Total Number of filing" FooterStyle-CssClass="fontcolor" ItemStyle-CssClass="txtcenter" HeaderText="Schedule1" ItemStyle-Width="6.9%">
<ItemTemplate>
<a id="wrapper1" href="Schedule12290.aspx?key=<%#Eval("form_key") %>" target="_blank">
<img src="<%#Eval("schedule1") %>" alt="" class="hover" />
<p class="text">Download Schedule 1</p>
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="5%" HeaderText="Copy" HeaderStyle-CssClass="nopad" ItemStyle-CssClass="txtcenter">
<ItemTemplate>
<asp:ImageButton ID="lnkDuplicate" runat="server"
ImageUrl="~/Images/grid/file_duplicate.png" OnClick="lnkbtnDuplicate_Click" ToolTip="Copy / Duplicate filing" CssClass='<%#Eval("duplicate") %>' OnClientClick="javascript:return confirm('Are you sure you want to copy from previous years filing?');" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="3%" HeaderText="Edit" ItemStyle-CssClass="txtcenter" HeaderStyle-CssClass="nopad" FooterStyle-CssClass="fontcolor txtcenter">
<ItemTemplate>
<asp:ImageButton ID="lnkBtnContinue" runat="server"
ImageUrl="~/Images/grid/edit3.png" OnClick="imgBtnContinue_Click" ToolTip="Edit" CssClass='<%# Eval("continue")%>' />
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="total" runat="server"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="8%" HeaderText="Delete" ItemStyle-CssClass="txtcenter" HeaderStyle-CssClass="nopad" FooterStyle-CssClass="hide">
<ItemTemplate>
<asp:ImageButton ID="imgBtnDel" runat="server"
ImageUrl="~/Images/grid/delBlue.png" OnClick="imgBtnDelete_Click" ToolTip="Delete" CssClass='<%#Eval("delete") %>' OnClientClick="javascript:return confirm('Do you want to delete this file permanently?');" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="line" />
</asp:GridView>
</div>
</div>
<div runat="server" id="divDetail" onmouseover="highlight(this, event)"
onmouseout="highlight(this, event)">
</div>
javascript code
<script type="text/javascript">
var iRowIndex; // THE ROW INDEX OF THE GRIDVIEW, TO KEEP THE ROW HIGHLIGHTING
// WHEN THE MOUSE IS ON ANOTHER CONTROL.
function MouseEvents(objRef, evt, desc) {
if (evt.type == "mouseover") {
objRef.style.cursor = 'pointer'
objRef.style.backgroundColor = "#EEE";
ShowDiv(desc, evt.pageY);
}
else {
objRef.style.backgroundColor = "#FFF";
iRowIndex = objRef.rowIndex;
HideDiv();
}
}
function ShowDiv(desc, pos) {
// SHOW THE DIV WITH DESCRIPTIONS NEXT TO THE SELECTED GRIDVIEW ROW.
document.getElementById('divDetail').style.display = 'block';
document.getElementById('divDetail').innerHTML = desc;
document.getElementById('divDetail').style.marginTop = pos - 25 + 'px';
}
function HideDiv() { document.getElementById('divDetail').style.display = 'none'; }
function highlight(objRef, evt) {
if (evt.type == "mouseover") {
objRef.style.display = 'block';
document.getElementById('gvEdit').rows[iRowIndex].style.backgroundColor = "#EEE";
}
else {
if (evt.type == "mouseout") {
document.getElementById('gvEdit').rows[iRowIndex].style.backgroundColor = "#FFF";
objRef.style.display = 'none';
}
}
}
and my css
<style type="text/css">
body
{
font-family:Arial, Tahoma;
font-size:15px;
}
#divDetail
{
float:left;
font:inherit;
font-size:13px;
padding:2px 5px;
width:auto;
border:solid 2px #CCC;
-moz-border-radius:0 7px 7px 0; -webkit-border-radius:0 7px 7px 0;
border-radius:0 7px 7px 0;
display:none;
color:#333;
}
#divDetail p {
font:inherit;
}
#divDetail a
{
font:inherit;
float:right;
background-color:#357AE8;
color:#FFF;
text-decoration:none;
border:solid 1px #2F5BB7;
border-radius:3px; -moz-border-radius:3px; -webkit-border-radius:3px;
padding:3px;
}
</style>
and my back end code aspx.cs
protected void gvEdit_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
String vd = System.String.Empty;
vd = "Vehicle Details";
Form objForm = new Form2290.Form();
objForm.FormID = DataBinder.Eval(e.Row.DataItem, "form_key").ToString();
BAL_F2290 objfrmkey = new BAL_F2290();
DataTable dt = objfrmkey.getmouseover(objForm);
if (dt.Rows.Count > 0)
{
foreach (DataRow ldr in dt.Rows)
{
vd = vd + "Reference : " + DataBinder.Eval(e.Row.DataItem, "ref_no").ToString();
vd = vd + "Vin : " + dt.Rows[0]["vin"];
vd = vd + "Category : " + dt.Rows[0]["category"];
vd = vd + "Is_Logging : " + dt.Rows[0]["is_logging"];
vd = vd + "Is_Agricultural : " + dt.Rows[0]["is_agricultural"];
vd = vd + "Weight : " + dt.Rows[0]["weight_current"];
vd = vd + "Tax_amt : " + dt.Rows[0]["tax_amt"];
}
e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event, '" + vd + "')");
e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event, '" + DataBinder.Eval(e.Row.DataItem, "ref_no").ToString() + "')");
}
}
}
One more Important point is i am not getting any error

The way you're doing it is very complicated and it really doesn't need to be this way.You can create a hidden column in your GridView and bind it to the required property on your datasource which contains the details data.Then using very minimal jQuery you can loop through the rows of the GridView -> extract the hidden comment -> set the tooltip of the row hover to this value or create some other event that shows a custom popup div with your comment.
Look how simple this is:
Code behind:
public partial class aGridViewDetailsHover : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
GridView1.DataSource = this.GetUsers();
GridView1.DataBind();
}
}
private List<MyUser> GetUsers()
{
var u1 = new MyUser { Name = "User1 Name", Surname = "User1 Surname", HiddenComment = "Hidden Comment For User 1" };
var u2 = new MyUser { Name = "User2 Name", Surname = "User2 Surname", HiddenComment = "Hidden Comment For User 2" };
var u3 = new MyUser { Name = "User3 Name", Surname = "User3 Surname", HiddenComment = "Hidden Comment For User 3" };
return new List<MyUser> { u1, u2, u3 };
}
}
public class MyUser
{
public string Name { get; set; }
public string Surname { get; set; }
public string HiddenComment { get; set; }
}
.ASPX:
<head runat="server">
<title></title>
<style type="text/css">
.hiddencol { display: none; }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('#GridView1 tr').each(function () {
var tr = $(this);
var children = $(tr).children();
var commentTd = children[2];
var comment = $(commentTd).html();
if (comment != "")
{
$(tr).prop("title", comment);
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" />
<asp:BoundField DataField="Surname" />
<asp:BoundField DataField="HiddenComment" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol" />
</Columns>
</asp:GridView>
</div>
</form>
</body>

Related

Get the Div Id inside the parent GridView by Javascript

I want to get the div with id forExport and the Hidden Field Value
<table width="100%">
<tr>
<td>
<asp:HiddenField ID="hidGridView" runat="server"/>
<asp:GridView ID="grvPayroll" CssClass="table table-striped table-bordered table-hover"
AllowPaging="true"
runat="server" AutoGenerateColumns="False" DataKeyNames="Id"
OnRowCancelingEdit="grvPayroll_RowCancelingEdit" OnRowDataBound="grvPayroll_RowDataBound"
OnRowEditing="grvPayroll_RowEditing" OnRowUpdating="grvPayroll_RowUpdating"
OnRowCommand="grvPayroll_RowCommand" ShowFooter="True" OnRowDeleting="grvPayroll_RowDeleting"
OnRowDeleted="grvPayroll_RowDeleted" OnRowUpdated="grvPayroll_RowUpdated"
OnPageIndexChanging="grvPayroll_OnPageIndexChanging" PageSize="5" OnRowCreated="grvPayroll_RowCreated">
<Columns >
<asp:TemplateField>
<ItemTemplate>
<a href="javascript:expandcollapse('div<%# Eval("Id") %>', 'one');">
<img id='imgdiv<%# Eval("Id") %>' alt="Click to show/hide Payroll Details <%# Eval("PayrollCode") %>" border="0" src="../App_Themes/Admin/img/plus.png"/>
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PayrollCode" SortExpression="PayrollCode">
<EditItemTemplate>
<asp:TextBox ID="txtPayrollCode" runat="server" Text='<%# Eval("PayrollCode") %>' CssClass="textbox"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvtxtPayrollCode"
runat="server" ControlToValidate="txtPayrollCode"
ErrorMessage="Required">
*
</asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewPayrollCode" runat="server" CssClass="textbox"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblPayrollCode" runat="server" Text='<%# Bind("PayrollCode") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Function" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="lbtUpdate" runat="server" CausesValidation="False" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="lbtCancel" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="lbtAddNew" runat="server" ToolTip="Add New" ImageUrl="../App_Themes/Admin/img/file_add.png" CausesValidation="False" CommandName="AddNew"/>
</FooterTemplate>
<ItemTemplate>
<asp:ImageButton ID="lbtEdit" runat="server" ToolTip="Edit" ImageUrl="../App_Themes/Admin/img/edit.png" CausesValidation="False" CommandName="Edit"/>
<asp:ImageButton ID="lbtDelete" runat="server" ToolTip="Delete" ImageUrl="../App_Themes/Admin/img/delete.png" OnClientClick=" return confirm('Are you sure you want to delete this?'); " CausesValidation="False" CommandName="Delete"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<tr>
<td colspan="100%">
<div id='div<%# Eval("Id") %>' style="display: none; left: 15px; OVERFLOW: auto; position: relative; WIDTH: 98%">
<div id="forExport">
<asp:GridView ID="grvPayrollDetails"
EmptyDataText="No Records Found" CellPadding="5" ForeColor="#333333" GridLines="Both" AllowPaging="False"
runat="server" AutoGenerateColumns="False" DataKeyNames="PayrollID"
OnRowDataBound="grvPayrollDetails_RowDataBound" OnRowCreated="grvPayrollDetails_RowCreated">
<AlternatingRowStyle CssClass="GridStyle_AltRowStyle2"/>
<HeaderStyle CssClass="GridStyle_HeaderStyle2"/>
<RowStyle CssClass="GridStyle_RowStyle2"/>
<Columns >
<asp:TemplateField HeaderText="Mã NV">
<ItemTemplate>
<asp:Label ID="plEmpID" runat="server" Visible="false" Text='<%# Eval("EmpID").ToString() %>'></asp:Label>
<%#get_EmpCode(Eval("EmpID").ToString()) %><br/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tổng chi phí">
<ItemTemplate>
<asp:Label ID="lblTotalPaymentCost" runat="server" Text='<%#Format_Money(Eval("TotalPaymentCost").ToString()) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
And this is the script:
<script type="text/javascript">
function expandcollapse(obj, row) {
var div = document.getElementById(obj);
var img = document.getElementById("img" + obj);
if (div.style.display == "none") {
div.style.display = "block";
if (row == "alt") {
img.src = "../App_Themes/Admin/img/minus.png";
} else {
img.src = "../App_Themes/Admin/img/minus.png";
}
img.alt = "Close to view other Payroll info";
} else {
div.style.display = "none";
if (row == "alt") {
img.src = "../App_Themes/Admin/img/plus.png";
} else {
img.src = "../App_Themes/Admin/img/plus.png";
}
img.alt = "Expand to show Payroll Details";
}
}
</script>
<script type="text/javascript">
function AssignExportHTML() {
document.getElementById('<%=hidGridView.ClientID%>').value = htmlEscape(forExport.innerHTML);
}
function htmlEscape(str) {
return String(str)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
</script>
I need to export the nested child gridview to excel with grouping (subtotal, Grand total), but when I export grouping row is only a blank row, so I try this code but it cannot work with nested gridview
So how to do, because when debugging, null value error occur. I think because Hidden Field value is null and I cannot get the div forExport in the Parent Gridview.And this is the code behind:
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
protected void ExportExcel(object sender, EventArgs e)
{
grvPayroll.AllowPaging = false;
var grvPayrollDetails = new GridView();
for (var i = 0; i < grvPayroll.Rows.Count; i++)
{
grvPayrollDetails = (GridView) grvPayroll.Rows[i].FindControl("grvPayrollDetails");
}
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=PayrollExport.xls");
Response.Charset = "UTF-8";
Response.ContentType = "application/vnd.ms-excel";
using (var sw = new StringWriter())
{
grvPayrollDetails.AllowPaging = false;
BindGrid(SortField);
grvPayrollDetails.Font.Name = "Times New Roman";
grvPayrollDetails.BackColor = Color.Transparent;
grvPayrollDetails.GridLines = GridLines.Both;
grvPayrollDetails.HeaderStyle.VerticalAlign=VerticalAlign.Middle;
sw.Write(System.Web.HttpUtility.HtmlDecode(hidGridView.Value));
Response.Write(Regex.Replace(sw.ToString(), "(<a[^>]*>)|(</a>)", " ", RegexOptions.IgnoreCase));
Response.Flush();
Response.End();
}
}
I referred this link :Exporting to Excel from GridView when grid changed by code behind
For accessing id of asp.net controls you have to use ClientID as below
document.getElementById('<%=hidGridView.ClientID%>').value = htmlEscape(document.getElementById("forExport").innerHTML);

Error: The name 'RGGSTAcCode' does not exist in the current context

In one of the webpage, I have RadGrid inside FormView Control
i.e., as below markup:
<asp:FormView ID="fvIPRForm" runat="server" DefaultMode="Insert" DataKeyNames="RequestID"
DataSourceID="odsIPRForm" EnableModelValidation="True" OnItemInserting="fvIPRForm_ItemInserting"
OnDataBound="fvIPRForm_DataBound" OnItemUpdating="fvIPRForm_Updating" OnItemCommand="fvIPRForm_ItemCommand">
<%-- Create New IPR--%>
<InsertItemTemplate>
<telerik:RadMultiPage ID="RadMultiPage5" runat="server" SelectedIndex="0" Width="100%">
<telerik:RadPageView ID="RadPageView4" runat="server" Width="100%">
<telerik:RadAjaxPanel ID="RadAjaxPanel4" runat="server">
//RadGrid
<telerik:RadGrid ID="RGGSTAcCode" runat="server" AutoGenerateColumns="false"....>
//other code
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" Text='<%# Eval("AccountCode") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="260"
AllowCustomText="true" onclienttextchange="OnClientTextChange">
</telerik:RadComboBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" OnClientClick="ButtonClicked()" UseSubmitBehavior="true" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
</telerik:RadPageView>
</telerik:RadMultiPage>
</InsertItemTemplate>
<%-- Edit IPR--%>
<EditItemTemplate>
<telerik:RadMultiPage ID="RadMultiPage5" runat="server" SelectedIndex="0" Width="100%">
<telerik:RadPageView ID="RadPageView4" runat="server" Width="100%">
<telerik:RadAjaxPanel ID="RadAjaxPanel4" runat="server">
//RadGrid
<telerik:RadGrid ID="RGGSTAcCode" runat="server" AutoGenerateColumns="false"....>
//other code
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" Text='<%# Eval("AccountCode") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="260"
AllowCustomText="true" onclienttextchange="OnClientTextChange">
</telerik:RadComboBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" OnClientClick="ButtonClicked()" UseSubmitBehavior="true" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
</telerik:RadPageView>
</telerik:RadMultiPage>
</EditItemTemplate>
<%-- View IPR--%>
<ItemTemplate>
<telerik:RadMultiPage ID="RadMultiPage5" runat="server" SelectedIndex="0" Width="100%">
<telerik:RadPageView ID="RadPageView4" runat="server" Width="100%">
<telerik:RadAjaxPanel ID="RadAjaxPanel4" runat="server">
//RadGrid
<telerik:RadGrid ID="RGGSTAcCode" runat="server" AutoGenerateColumns="false"....>
//other code
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" Text='<%# Eval("AccountCode") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="260"
AllowCustomText="true" onclienttextchange="OnClientTextChange">
</telerik:RadComboBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" OnClientClick="ButtonClicked()" UseSubmitBehavior="true" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
</telerik:RadPageView>
</telerik:RadMultiPage>
</ItemTemplate>
</asp:FormView>
Now, I try to get the RadGrid -- EditItemTemplate -- Button control
inside JavaScript to make it visible true/false based on text length that user enter in RadComboBox.
Below is my JavaScript:
<script lang="javascript" type="text/javascript">
function OnClientTextChange(sender, eventArgs) {
//alert("You typed " + sender.get_text());
var len = sender.get_text().length;
alert(len);
var form = $find("<%#RGGSTAcCode.ClientID%>").get_masterTableView();
alert(form);
}
</script>
When I run my web page, I always get below error:
The name 'RGGSTAcCode' does not exist in the current context
I tried to change the JavaScript code as below:
var form = document.getElementById('<%=fvIPRForm.FindControl("RGGSTAcCode").ClientID%>');
var masterTable = form.get_masterTableView();
alert(masterTable);
but then I get [object Object] in "alert". What is wrong in my code?
Edit
Tried below solution, all working except Buttons are not disabled/enabled inside if/else:
function onTextChange(sender, args) {
//alert("You typed " + sender.get_text());
var len = sender.get_text().length;
alert(len);
var comboID = sender.get_id();
var btnSearchID = comboID.replace("ddlAccountCode", "btnSearch");
alert("Alert 1: " + btnSearchID); //getting : contentplaceholder_fviIPRForm_RGGSTAcCode_btnSearch
var btnCtrl = $get(btnSearchID);
alert("Alert 2: " + btnCtrl); //getting : [object HTMLInputElement]
if (len > 5)
{
alert("greater");
btnCtrl.set_enabled(true);
btnsearch.set_enabled(true); // enable search button
}
else
{
alert("less");
btnCtrl.set_enabled(false);
btnsearch.set_enabled(false); // disable search button
}
}
This might be the answer you want....
Not the best but is working..
.aspx
<asp:FormView ID="fv" runat="server" DefaultMode="Insert" OnDataBound="fv_DataBound">
<InsertItemTemplate>
<telerik:RadMultiPage ID="RadMultiPage5" runat="server"
SelectedIndex="0" Width="100%">
<telerik:RadPageView ID="RadPageView4" runat="server" Width="100%">
<telerik:RadAjaxPanel ID="RadAjaxPanel4" runat="server">
<telerik:RadGrid ID="RadGrid1" runat="server"
AutoGenerateColumns="false"
OnNeedDataSource="RadGrid1_NeedDataSource">
<MasterTableView>
<Columns>
<telerik:GridTemplateColumn HeaderText="Acc">
<ItemTemplate>
<asp:Label ID="lbl" runat="server"
Text='<%# Eval("Acc") %>'></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode"
runat="server" Height="200" Width="260"
AllowCustomText="true"
OnClientTextChange="onTextChange">
<Items>
<telerik:RadComboBoxItem Text="Gg" />
<telerik:RadComboBoxItem Text="Gg1" />
<telerik:RadComboBoxItem Text="Gg3" />
</Items>
</telerik:RadComboBox>
<telerik:RadButton ID="btnSearch" runat="server" Text="Search" />
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
</telerik:RadPageView>
</telerik:RadMultiPage>
</InsertItemTemplate>
</asp:FormView>
Javascript
<telerik:RadCodeBlock ID="rcb" runat="server">
<script type="text/javascript">
function onTextChange(sender, args) {
var grid = $find('<%=fv.FindControl("RadGrid1").ClientID %>');
var gridMasterData = grid.get_masterTableView();
var dataItem = gridMasterData.get_dataItems();
var length = dataItem.length;
// Loop
for (var i = 0; i < length; i++) {
// Find Control
var comboBox = dataItem[i].findControl("ddlAccountCode");
// Check
if (comboBox != undefined) {
if (sender.get_id() == comboBox.get_id()) {
// Find Button
var btn = dataItem[i].findControl("btnSearch");
var item = sender.get_text();
// Check
if (item.length > 5) {
if (btn != undefined) btn.set_visible(true);
}
else btn.set_visible(false);
break;
}
else
continue;
}
}
}
</script>
</telerik:RadCodeBlock>
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
dt.Columns.Add("Acc");
dt1.Columns.Add("a");
// Loop
for (int i = 0; i < 2; i++)
dt.Rows.Add("a " + i);
dt1.Rows.Add("AAAA");
ViewState["Data"] = dt;
// Bind
fv.DataSource = dt1;
fv.DataBind();
dt.Dispose();
dt1.Dispose();
}
}
protected void fv_DataBound(object sender, EventArgs e)
{
// FindControl
RadGrid RadGrid1 = fv.FindControl("RadGrid1") as RadGrid;
// Check
if (RadGrid1 != null)
{
RadGrid1.DataSource = ViewState["Data"] as DataTable;
RadGrid1.DataBind();
}
}
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
RadGrid rg = fv.FindControl("RadGrid1") as RadGrid;
// Check
if (rg != null)
{
rg.DataSource = ViewState["Data"] as DataTable;
}
}
Below code is working fine based on my requirement:
function onTextChange(sender, args) {
var len = sender.get_text().length;
//alert(len);
var comboID = sender.get_id();
var btnSearchID = comboID.replace("ddlAccountCode", "btnSearch");
var btnCtrl = document.getElementById(btnSearchID);
if (len >= 5)
{
btnCtrl.disabled = false;
//btnCtrl.style.display = "";
}
else
{
btnCtrl.disabled = true;
//btnCtrl.style.display = "none";
}
}

How to use the Jquery Shake effect on Button click?

What i want to do is to shake the textbox if the textbox is empty. But i a unable to do this.
What i am doing is as follows :
$("#BtnSubmit").click(function() {
if ($("#txt1").val() == '' || $("#TextBox1").val() == '' || $("#TextBox2").val()) {
$("#txt1").effect("shake")
}
});
<div id="keepTextBox">
<asp:TextBox ID="txt1" ForeColor="White" runat="server" Height="30px" Style="background-color: #46375E;"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="txt1" ID="rftxt1" runat="server" SetFocusOnError="true"></asp:RequiredFieldValidator>
<asp:TextBox ID="TextBox1" ForeColor="White" runat="server" Height="30px" Style="background-color: #46375E"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="TextBox1" ID="rfTextBox1" runat="server"
SetFocusOnError="true"></asp:RequiredFieldValidator>
<asp:TextBox ID="TextBox2" runat="server" ForeColor="White" Height="30px" Style="background-color: #46375E"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="TextBox2" ID="rfTextBox2" runat="server"
SetFocusOnError="true"></asp:RequiredFieldValidator>
<asp:Button ID="BtnSubmit" runat="server" Width="15%" Text="SIGN UP" ForeColor="White"
Style="background-color: #49A7E4; cursor: pointer;" Height="40px" /></div>
</div>
You have to include jquery UI as dependency along with jquery to get the shake effect.
$("#txt1").click(function() {
$(this).effect( "shake" );
});
<button id="txt1">shake it</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
OR
if you dont want to include Jquery UI, then you will have to implement it as seen in this answer on SO.
$("#txt").click(function(){
$(this).shake();
});
<button id="txt">shake it</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery.fn.shake = function(intShakes, intDistance, intDuration) {
intShakes = intShakes || 10;
intDistance = intDistance || 2;
intDuration = intDuration || 1000;
this.each(function() {
$(this).css("position","relative");
for (var x=1; x<=intShakes; x++) {
$(this).animate({left:(intDistance*-1)}, (((intDuration/intShakes)/4)))
.animate({left:intDistance}, ((intDuration/intShakes)/2))
.animate({left:0}, (((intDuration/intShakes)/4)));
}
});
return this;
};
</script>

Enable/Disable Validators in Gridview when adding row dynamically

I have issue to disable/enable validators for newly add row to gridview which is in Update panel, If I remove Update panel then it's worked perfect, and If I add Update panel then it stops working. I have created sample page.
Default.aspx.
<head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('table > tbody > tr .wrapper [class*="onoff"] option:selected').each(function (index) { adjustValidators(this); }); $('[class*="onoff"] select').change(function () { adjustValidators($('option:selected', this)[0]); }); }); </script></head>
<ajax:ToolkitScriptManager runat="server" ID="RadScriptManager1" AsyncPostBackTimeout="18000"> </ajax:ToolkitScriptManager><asp:MultiView ID="MultiView1" runat="server"> <asp:View ID="group_Group1" runat="server"> <div class="group group1"> <asp:Button ID="btnNext0_top" runat="server" Text="Next >>" OnClick="btnNext_Click" ValidationGroup="surveyValidate0" /> <asp:UpdatePanel runat="server" ID="UPNew" UpdateMode="Conditional"> <ContentTemplate> <asp:GridView runat="server" ID="repeatregion_RRSectionSS" RegionName="RRSectionSS" AutoGenerateColumns="False" GridLines="None" CellSpacing="-1" CssClass="rrsectionss"> <Columns> <asp:TemplateField> <ItemTemplate> <div id="wrapper_ONOFF" runat="server" class="wrapper onoff"> <div class='statement onoff' id="statement_ONOFF" runat="server"> Required Validator :</div> <div class='question onoff' id="questionlayer_ONOFF" runat="server"> <asp:DropDownList runat="server" ID="question_ONOFF" ValidationGroup="surveyValidate0" Data='<%# Eval("ONOFF") %>' Val='<%# Eval("ONOFF_selectedValue") %>'> <asp:ListItem Text="Off" Value="-1"></asp:ListItem> <asp:ListItem Value="1" Text="On"></asp:ListItem> </asp:DropDownList> </div> </div> <div id="wrapper_testsssss" runat="server" class="wrapper testsssss"> <div class='statement testsssss' id="statement_testsssss" runat="server"> Sample Text </div> <div class='question testsssss' id="questionlayer_testsssss" runat="server"> <asp:TextBox runat="server" ID="question_testsssss" type="shortans" Columns='40' ValidationGroup="surveyValidate0" Text='<%# Common.DecodeXML(Eval("testsssss")) %>'></asp:TextBox> <asp:RequiredFieldValidator ID="rfv_question_testsssss" runat="server" ValidationGroup="surveyValidate0" SetFocusOnError="true" EnableClientScript="true" ControlToValidate="question_testsssss" Display="Dynamic" Text="**" ErrorMessage="**" /> </div> </div> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:Button runat="server" ID="btnAddClick" Text="Add Section" OnClick="btn_Click" /> </ContentTemplate> </asp:UpdatePanel> </div> </asp:View> <asp:View ID="group_Group2" runat="server"> <div class="group group2"> <asp:Button ID="btnPrevious1_top" runat="server" Text="<< Prev" OnClick="btnPrevious_Click" /> <asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="surveyValidate1" /> </div> </asp:View> </asp:MultiView>
<script type="text/javascript"> function pageLoad(sender, args) { if (args.get_isPartialLoad()) { $('table > tbody > tr .wrapper [class*="onoff"] option:selected').each(function (index) { adjustValidators(this); }); } } function adjustValidators(ctrl) { var id = ctrl.parentNode.id.replace('_question', '_rfv_question').replace('ONOFF', 'testsssss') // alert(ctrl.value); if (ctrl.value == -1) { ValidatorEnable(eval(id), false) } else { ValidatorEnable(eval(id), true) } } </script>
Default.aspx.cs.
protected void Page_Load(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = (MultiView1.ActiveViewIndex == -1) ? 0 : MultiView1.ActiveViewIndex;
DataTable objData =new DataTable();
if (ViewState["data"] != null)
{
objData = (DataTable)ViewState["data"];
}
else
{
objData = new DataTable();
objData.Columns.Add("testsssss");
objData.Columns.Add("ONOFF");
objData.Columns.Add("ONOFF_selectedValue");
objData.Rows.Add(objData.NewRow());
ViewState["data"] = objData;
}
if (!IsPostBack)
{
repeatregion_RRSectionSS.DataSource = objData;
repeatregion_RRSectionSS.DataBind();
}
}
protected void btnNext_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex += 1;
}
protected void btnPrevious_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex -= 1;
}
protected void btn_Click(object sender, EventArgs e)
{
DataTable objData = (DataTable)ViewState["data"];
objData.Rows.Add(objData.NewRow());
repeatregion_RRSectionSS.DataSource = objData;
repeatregion_RRSectionSS.DataBind();
ViewState["data"] = objData;
}
when Click on add then item get added to gridview but validators are not disabled.
Thanks and Regards
Sadiq Modan
After some research and trickery I found the solution: replace eval in ValidatorEnable(eval(id), false) with document.getElementById(id). It worked for me.

validate radiobuttonlist in a gridview using javascript

I am trying to validate that each radiobuttonlist has been selected. the radiobuttonlist is dynamically created from a sql database. The following line errors out "if (MyRadio[j].checked) {", the error is "checked' is null or not an object". The following is the code. Thank you
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" runat="Server">
<cc1:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="0" CssClass="ajax__myTab" Width="100%" ScrollBars="Horizontal">
<cc1:TabPanel ID="TabPanel1" runat="server" HeaderText="" Enabled="true">
<HeaderTemplate>Main</HeaderTemplate>
<ContentTemplate>
<table cellpadding="3" cellspacing="1">
<tr>
<td style="text-align: right">Audit Status:</td>
<td>
<asp:DropDownList ID="ddlAuditStatus" runat="server">
<asp:ListItem>InProgress</asp:ListItem>
<asp:ListItem>Completed</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</table>
</ContentTemplate>
</cc1:TabPanel>
<cc1:TabPanel ID="TabPanel2" runat="server" HeaderText="" Enabled="true">
<HeaderTemplate>Questions</HeaderTemplate>
<ContentTemplate>
<asp:GridView ID="GridViewQuestions" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="5" CellSpacing="1" DataKeyNames="Pkey" DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="Vertical">
<FooterStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblQuestion" runat="server"></asp:Label>
<asp:HiddenField ID="hdnPkey" runat="server" Value='<%# Bind("Pkey") %>' />
<asp:HiddenField ID="hdnRequiresAnAnswer" runat="server" Value='<%# Bind("RequiresAnAnswer") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Answer">
<ItemTemplate>
<asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatDirection="Horizontal" Visible="false">
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
<asp:ListItem>N/A</asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
<HeaderStyle Width="130px" />
<ItemStyle Width="130px" />
</asp:TemplateField>
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Silver" Font-Bold="True" ForeColor="Black" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
</ContentTemplate>
</cc1:TabPanel>
</cc1:TabContainer>
<script type="text/javascript">
function fcnUpdateMain() {
var MyStatus = document.getElementById("<%=ddlAuditStatus.ClientID%>").value
var grid = document.getElementById("<%= GridViewQuestions.ClientID %>");
if (grid.rows.length > 0) {
for (i = 2; i < grid.rows.length + 1; i++) {
if (i < 10) {
i = "0" + i
} else {
i = i
}
var MyReqAnswer = document.getElementById("ctl00_ContentPlaceHolder2_TabContainer1_TabPanel2_GridViewQuestions_ctl" + i + "_hdnRequiresAnAnswer").value
var MyRadio = document.getElementById("ctl00_ContentPlaceHolder2_TabContainer1_TabPanel2_GridViewQuestions_ctl" + i + "_RadioButtonList1")
if (MyStatus == "Completed") {
if (MyReqAnswer == "Yes") {
var options = document.getElementsByTagName("input")
for( x = 0; x < options.length; ++x ) {
if(options[x].type == "radio") {
for (var j = 0; j < MyRadio.length; j++) {
if (MyRadio[j].checked) {
} else {
alert("You must select an answer for all questions.")
document.getElementById("ctl00_ContentPlaceHolder2_TabContainer1_TabPanel2_GridViewQuestions_ctl" + i + "_ddlProductInterest").focus()
return false;
}
}
}
}
}
}
}
}
}
</script>
I think you've already realised that RadioButtonList controls are rendered as a <table> with each radio button as an <input> within that table. Therefore getting a handle on RadioButtonList1 and trying to access it as an array using MyRadio[j] isn't going to work.
I think the following line:
var options = document.getElementsByTagName("input")
Should instead read:
var options = MyRadio.getElementsByTagName("input")
That will give you just a collection of the input tags within that RadioButtonList control rather than all those on the page. Once you have that options collection, you shouldn't need to refer to the RadioButtonList control again.
I understand that this is drastically simplified over what you have, but here's an example for you:
<form runat="server">
<asp:RadioButtonList runat="server" id="RadioButtonList1">
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
<asp:ListItem>N/A</asp:ListItem>
</asp:RadioButtonList>
<input type="button" onclick="fcnUpdateMain()" value="Click" />
<script type="text/javascript">
function fcnUpdateMain()
{
var MyRadio = document.getElementById("<%=RadioButtonList1.ClientID%>")
var options = MyRadio.getElementsByTagName("input")
var somethingChecked = false;
for( x = 0; x < options.length; ++x )
{
if (options[x].checked)
{
somethingChecked = true;
}
}
if (!somethingChecked)
{
alert("You must select an answer for all questions.")
return false;
}
}
</script>
</form>

Categories