I am trying to capture in google analytics the data that is entered into a textbox. The code that I have so far is below, I am trying to capture the data by Javascript, but I can't seem to get it to work. The CMS Platform I am using is sitecore.
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="SalesRepSearch.ascx.cs" Inherits="USEndoscopy.Website.layouts.USEndoscopy.Sublayouts.SalesRepSearch" %>
<%# Import Namespace="USEndoscopy.Library.Search" %>
<script type="text/javascript">
var textbox = document.getElementById('txtZipCode'),
submitButton = document.getElementById('btnSalesRepSearch');
submitButton.onClick = function () {
_trackEvent('data-store', textbox.name, textbox.value, 0);
// 'data-store' can be replaced with whatever category of data you want, for sortability's sake
// the 0 can be replaced with any other numerical data you want - but it must be numerical
}
</script>
<p></p>
<p>
<asp:Panel DefaultButton="btnSalesRepSearch" runat="server">
<asp:TextBox ID="txtZipCode" runat="server" Width="300px"></asp:TextBox>
<asp:Button ID="btnSalesRepSearch" runat="server" CssClass="buttonregular" Text="Search" OnClick="btnSalesRepSearch_Click" />
<asp:RequiredFieldValidator ID="reqTxtZipCode" runat="server" ValidationGroup="ZipCode" ControlToValidate="txtZipCode" Display="Dynamic" ErrorMessage="Please enter a valid US Zip code" CssClass="error"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regExTxtZipCode" runat="server" ValidationExpression="^\d {5}(-\d{4})?$" ValidationGroup="ZipCode" ControlToValidate="txtZipCode" Display="Dynamic" ErrorMessage="Please enter a valid US Zip code" CssClass="error"></asp:RegularExpressionValidator>
</asp:Panel>
</p>
<p>
<asp:Repeater ID="salesRepContainer" runat="server">
<ItemTemplate>
<%# ((SalesRep)Container.DataItem).RepName %><br />
<%# ((SalesRep)Container.DataItem).Phone %><br />
<%# ((SalesRep) Container.DataItem).Email %><br />
</ItemTemplate>
</asp:Repeater>
</p>
<p>
<sc:Text Field="InternationalMessage" runat="server" />
</p>
Did you check the source code of the rendered HTML? Has the ASP.Net WebControl ID's ended up as something completely different due being nested in the panel?
Maybe you should add a CSS class to these and use document.getElementsByClassName
If you are using jQuery then you could use the attributeEndsWith selector
$('input[id$="txtZipCode"]');
$('input[id$="btnSalesRepSearch"]')
It's because ASP.NET has changed the ID value of your textboxes at the time of rendering them.
If your running .net V4 or greater then add ClientIDMode="Static" to your textbox and
button. This tells .net to not change the ID of your control.
<asp:TextBox ID="txtZipCode" runat="server" ClientIDMode="Static" Width="300px"></asp:TextBox>
<asp:Button ID="btnSalesRepSearch" runat="server" ClientIDMode="Static" CssClass="buttonregular" Text="Search" OnClick="btnSalesRepSearch_Click" />
If your running less than .net 4 change your Javascript to: (.ClientID gets the ID that .net gave the control when it rendered it)
var textbox = document.getElementById('<%= txtZipCode.ClientID %>'),
submitButton = document.getElementById('<%= btnSalesRepSearch.ClientID %>');
UPDATE
You might be having an issue where your javascript function is trying to assign a click function to your button before your button is actually available on the DOM.
So try the following:
Javascript function
function btnSearchClick(){
var textbox = document.getElementById('txtZipCode');
// Change your google code to this:
_gaq.push(['_trackEvent', textbox.name, textbox.value, 0]);
return true;
}
And on your button add the property
onClientClick="return btnSearchClick()"
Related
On client side button click event, I want to get control id that are place in Item template of Grid View. I tried this code but it doesn't work. Thanks
function buttonClicked(sender, args) {
var gv = $find('<%= GridView1.ClientID %>');
var textbox = $GridView1.findControl(gv.get_element().parentNode, "Textbox");
}
Here is the Gridview
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1"runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="upTest" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="KurzDS" DataKeyNames="Id" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="Textbox" runat="server" Text="Textbox"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="Textbox1" runat="server" Text="Textbox1"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn" Text='btn' CommandArgument='<%# Eval("Id")%>' CommandName="btn" runat="server" CausesValidation="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
Thanks for including the GridView example. Now that I can see what you are attempting, I have a much better answer for you.
First, make a slight change to the button template, change out CommandArgument for OnClientClickand since you are using this button client side instead of posting back to the server, you can simplify it like this:
<asp:Button ID="btn" Text='btn' OnClientClick='<%# Eval("ID", "YourJavascriptFunction({0} - 1); return false;") %>' runat="server" CausesValidation="false" />
I have the click event call your JavaScript function and it sends in a parameter of the server side resolved id. Notice I subtract 1 first though. This is because the server side ASP.Net Eval function give the ID starting at 1. But, each of the ids that get generated for your text input elements start with a zero base.
Now look at the JavaScript function below.
// Clicking the first button sends in a 0, second sends in a 1, etc.
function YourJavascriptFunction(id) {
// each of the TextBox1 elements has an ASP.Net server side
// generated id that ends with GridView2_Textbox1_0,
// GridView2_Textbox1_1, etc.
let selectId = "input[id$='GridView2_Textbox1_" + id + "']";
// The text we use in the querySelector function states
// find the DOM element with a tag of "input" where the id
// ends with . . . The $ in id$= is the part that says the
// value must "end with"
let textBox1 = document.querySelector(selectId);
// Now that we have TextBox1 from the same row as the button,
// getting the value is easy.
alert(textBox1.value);
}
I left off a jQuery example as this querySelector command works in almost every browser including IE8 and above, so you shouldn't need jQuery for something this simple.
Let me know if I can help further.
I have a simple web page that has few asp panels. I make a search of record from database and these panels are made visible on the page.
but when, say, i enter an invalid value in the textbox to check whether the RequiredFieldValidator is working fine or not, the Error message is displayed. But the Panels that are already visible on the form are not hidden.
I understand, that because the form is not making a post back, therefore these panels are not set to invisible. Can something please guide me as to how to hide these panels if the requiredfieldvalitor throws an error?
You would either have to disable ClientValidation to allow a postback, or use custom JavaScript. If a visible postback is an issue, you can easily use UpdatePanels.
Attach dependent elements by data-dependentClass of validator and place this script below form closing tag
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
Text="*" data-dependentClass="addressValidation" />
<br />
<asp:TextBox ID="TextBox2" runat="server" />
<br />
<asp:Button runat="server" Text="Click Me" />
<hr />
<asp:Panel runat="server" ID="Panel1" CssClass="addressValidation">
Rendered at:
<%= DateTime.Now.ToLongTimeString() %>
</asp:Panel>
</form>
<script type="text/javascript">
var originalValidatorUpdateDisplay = ValidatorUpdateDisplay;
ValidatorUpdateDisplay = function (val) {
originalValidatorUpdateDisplay.call(null, val);
var dependentClass = val.getAttribute("data-dependentClass");
if (dependentClass) {
elements = document.getElementsByClassName(dependentClass);
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = val.isvalid === false ? "none" : "";
}
}
}
</script>
I'm having surprisingly bad luck finding a decent resource for this. But What I'm doing is creating a list of tickets using a ListView. One of the controls in the item template is a link button that shows the header of the ticket. When the user clicks the link button, I want to open a modal window that shows the ticket in readable format. To get the ticket, I'll be passing that page a variable and it'll do the rest; nothing complicated. The page will have 3 buttons and the windows needs to close when you click one of them.
Now, I figured out how to use the ModalPopupExtender from the Ajax tookit more or less. You create the panel in it's own div which stays hidden. I created a click event that basically uses a webclient to download the html from the page and insert it into that div's innerHtml. This seems to work the first time. But as soon as you click a different link, the page pukes and says something about it being in an illegal state.
I'm not sure if I'm going about this wrong, and I can't find any decent examples of how to do this. Well there's one, but the english is hard to understand and it's in VB instead of C#. Any help?
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<form id="form1" runat="server">
<div>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<br />
<asp:ModalPopupExtender
DropShadow="true"
OkControlID="btnOk"
CancelControlID="btnClose"
runat="server"
PopupControlID="Panel1"
id="ModalPopupExtender1"
TargetControlID="Button1" />
<asp:Panel ID="Panel1" runat="server" CssClass="modalPopup" style="display:none;">
This is basic modal popup.
<br /><br />
<asp:Button ID="btnOk" runat="server" Text="Ok" />
<asp:Button ID="btnClose" runat="server" Text="Close Me" />
<iframe src="http://www.google.com"></iframe>
</asp:Panel>
<asp:Button ID="Button1" runat="server" Text="First Modal Popup" />
</div>
</form>
Try this it should work.
<div>
<asp:Label ID="lblClientId" runat="server" CssClass="label" meta:resourcekey="lblClientIdResource" />
<asp:TextBox ID="tbClientId" runat="server" style="width:150px; "/>
<asp:Button ID="btnClientId" runat="server" style="width:50px;" meta:resourcekey="btnClientIdResource" />
<asp:CustomValidator ID="rfvClientId" runat="server" ValidationGroup="ClientId" meta:resourcekey="rfvClientIdResource" ControlToValidate="tbClientId" ClientValidationFunction="BtnClickClientId" style="position:absolute;" ValidateEmptyText="True" ><asp:Image ID="Image2" ImageUrl="caution_20.png" runat="server" /></asp:CustomValidator>
</div>
<script type="text/javascript">
function BtnClickClientId(session, args) {
ButtonClick(session, args, "<%= tbClientId.ClientID %>", "<%= lblClientId.ClientID %>");
}
window.onload = function () {
document.getElementById('<%= tbClientId.ClientID%>').focus();
};
</script>
<asp:ValidationSummary ID="ClientIdValidationSummary" runat="server" BackColor="LightGray" DisplayMode="BulletList" CssClass="validationSummary" EnableClientScript="true" HeaderText='<%$ Resources:GlobalResource, ValidationSummaryResource %>'/>
So this ButtonClick() method is working and has been tested independently. The problem is that when i enter nothing into the text box and click the button, the validator works as expected and appears on the screen. Then it disappears. It is also never shown in the page validation summary. How do I get this to work?
I have tried to also set a required field validator on this text box and it seems to work with that but I do not want to use two validators.
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="tbClientId" ErrorMessage="RequiredFieldValidator" style="position:absolute;"><asp:Image ID="Image2" ImageUrl="caution_20.png" runat="server" /></asp:RequiredFieldValidator>
<asp:CustomValidator ID="rfvClientId" runat="server" ValidationGroup="ClientId" meta:resourcekey="rfvClientIdResource" ControlToValidate="tbClientId" ClientValidationFunction="BtnClickClientId" style="position:absolute;" ValidateEmptyText="True" ></asp:CustomValidator>
This code works but I should not have to use 2 validators.
You need to set the "arg.IsValid" to "true" or "false" in the javascript function based on your requirement (i.e. to "true" when you think the validation is successful and false otherwise). Also, in the code behind file, it is always advisable to check for "Page.IsValid" property inside the click event handler of the button. So, in the javascript add this.
arg.IsValid = false;
and in code behind
protected void button_click(..)
{
if (Page.IsValid)
{
// Your code, if any exists
}
}
Hope this helps!!
Say I have one full-page form, but within the form, there are two or more events that need to take place on submission: Login & Register
Site.Master:
<%# Master Language="C#" AutoEventWireup="true"
EnableViewState="true" CodeBehind="Site.Master.cs"
Inherits="Site.SiteMasterPage" %>
<!doctype>
<html>
<head runat="server">
<%-- stuff --%>
</head>
<body>
<form ID="MainForm" action="" runat="server">
<asp:Login id="LoginControl" runat="server" />
<asp:CreateUserWizard id="RegisterControl" runat="server" />
</form>
</body>
</html>
If my cursor is focused inside of an input type="text" for asp:Login, and I hit Return (with javascript off), the page submits, but I am not logged in.
The same thing happens when I attempt to register (filling out the createUserWizard and hitting the Return key instead of actually clicking "Register", firing some event)
Is there any non-JavaScript solution for getting the Return key to submit the proper, currently focused portion of the form?
The panel control allows you to define a default button within the scope of it's contents:
<asp:Panel runat="server" DefaultButton="submitButtonA">
<asp:LinkButton ID="submitButtonA" runat="server" Text="Submit A"/>
</asp:Panel>
<asp:Panel runat="server" DefaultButton="submitButtonB">
<asp:LinkButton ID="submitButtonB" runat="server" Text="Submit A"/>
</asp:Panel>
The default button sounds like it might be your friend tonight - http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlform.defaultbutton.aspx
Actually it might not be, I haven't ever tried it with no Javascript.