Substitute TextBox value in javascript - javascript

I came across a scenario where i need to store value of Textbox in session variable in OnChange Event of TextBox1 .
How can i store content of x in Session Variable .
//JavaScript
function TextBox1_TextChanged() {
var x = document.getElementById("TextBox1").value;
var SesVar = "'<%= Session["HitCount"] = x %>'";
alert(SesVar);
// HTML
<asp:TextBox ID="TextBox1" Name="TextBox1" runat="server"
onchange="TextBox1_TextChanged()"></asp:TextBox>
Please suggest how to solve the above problem ?

You cannot do that.
As page comes from server , server code is executed first then the client code takes care of the rest.
If you need to do what you intend to do, then in the form create a hidden element with that value and get that element via GET or POST Global variables and store them in session.
<form method="get" action="destination.asp">
<input id="tb1value" name="test" visibility="hidden"></input>
</form>
Once you submit we use javascript(or jquery which is js library) to generally we put the value needed into that hidden value and send to server.
In your case,you just need the textbox to be used directly,form will do the job.
This tutorial might help you

you can not set it directorly.
There are two ways of doing this.
First set AutoPostBack to true
As follows
<asp:TextBox ID="TextBox1" Name="TextBox1" runat="server" AutoPostBack='true'
onchange="TextBox1_TextChanged"></asp:TextBox>
and in C# (code behind) on TextBox1_TextChanged write your code to set it in the session

I found solution of my problem.
function TextBox1_TextChanged() {
<%
// c# code to store value runtime in session variable .
Session["HitCount1"] = TextBox1.Text ;
%>
}
<body>
<form id="form1" runat="server">
<div>
<%
// C# code to retrieve session variable value .
string x = null;
x = Session["HitCount1"].ToString().Trim();
if ((x.Equals(null)) || (x.Equals("")))
{
// Session Variable is either empty or null .
TextBox1.Text = "";
}
else
{
TextBox1.Text = Session["HitCount1"].ToString();
}
%>
<asp:TextBox ID="TextBox1" Name="TextBox1" runat="server"
AutoPostBack='true' onchange="TextBox1_TextChanged()"></asp:TextBox>
</form>
</body>

// I Found another solution using cookie .
// test.aspx code
<script language="javascript" type="text/javascript">
function writeCookie(name,value,days) {
var date, expires;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}else{
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var i, c, ca, nameEQ = name + "=";
ca = document.cookie.split(';');
for (i = 0; i < ca.length; i++)
{
c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length,c.length);
}
}
return '';
}
function restore(){
var sId = readCookie('sessionId');
document.getElementById("TextBox1").value = sId ;
}
function backup() {
var sId = document.getElementById("TextBox1").value;
writeCookie('sessionId', sId, 3);
}
function getMyvalSession() {
var ff = "Loading Value";
return ff;
}
function TextBox1_TextChanged() {
backup();
}
</script>
<body onload="restore()">
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" Name="TextBox1" runat="server"
AutoPostBack="True" onchange="TextBox1_TextChanged()" ></asp:TextBox>
</div>
</form>
</body>
// test.aspx.cs code
protected void Page_Load(object sender, EventArgs e)
{
Loading();
}
void Loading (){
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession() ; ";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}
}

Related

Javasript cannot called in asp content

I'm trying to encrypt the textbox when it sends, what I'm trying to do is get the text encrypt and return the encrypted test to the textbox when the button is pressed, this is the code:
the javascript
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
--all the textbox is here
<asp:Button ID="btnSave" runat="server" CssClass="button" Text="Submit" OnClick="btnSave_Click"></asp:Button>
<script src="../Scripts/jquery-1.10.2.js" ></script>
<script type="text/javascript" language="javascript">
function encrypt(old,new,confirm)
{
if (document.getElementById("<%=txtOldPassword.ClientID%>").value != "")
{
document.getElementById("<%=txtOldPassword.ClientID%>").value = old;
}
if (document.getElementById("<%=txtNewPassword.ClientID%>").value != "")
{
document.getElementById("<%=txtNewPassword.ClientID%>").value = new;
}
if (document.getElementById("<%=txtNewPwdConfirm.ClientID%>").value != "")
{
document.getElementById("<%=txtNewPwdConfirm.ClientID%>").value = confirm;
}
alert("TextBox Value is " + txtOldPassword.value);
}
</script>
</asp:Content>
my javascript inside the asp:content, this is my backend code
protected void btnSave_Click(object sender, EventArgs e)
{
btnSave.Attributes.Add("OnClientClick", "javascript:return encrypt('" + old() + "','" + newpass() + "','" + conf() + "');");
}
private string old()
{
string old = Encrypt(txtOldPassword.Text);
return old;
}
private string newpass()
{
string newpass = Encrypt(txtNewPassword.Text);
return newpass;
}
private string conf() {
string conf = Encrypt(txtNewPwdConfirm.Text);
return conf;
}
why when I try to click the save button the textbox is not encrypted, I try to call the javascript it seems that asp: content does not detect javascript.

Adding Hyperlinks to ValidationSummary using programatically added validators

I'm using the javascript from the answer in this question in a project of mine:
Adding Hyperlinks to ValidationSummary
It works really great. I've added it to the bottom of my masterpage (for some reason, even though it is inside $(document).ready, Page_Validators is null if i place it in the head section)
Anyway! I'm also adding some custom validators programatically on postback using this code:
public static CustomValidator ReturnErrorMessage(string message, string validationGroup, string controlToValidate = "")
{
CustomValidator control = new CustomValidator();
control.ID = "cv" + controlToValidate;
control.IsValid = false;
control.Text = " ";
control.ValidationGroup = validationGroup;
control.ErrorMessage = message;
control.ControlToValidate = controlToValidate;
return control;
}
However whenever I add a CustomValidator like that, in a button event, page_load or whatever, Page_Validators will be overridden and the errormessage will revert to the message without a anchor.
What gives? Am I doing something wrong or can someone explain what is happening?
I've tried debugging it and it does set the values correctly, but then it just reset afterwards.
I've tried for the heck of it and in $(document).ready set all validators as isvalid = false, and that gets overwritten too.
Im using asp.net 4.5 unobtrusive validation, but it does not make a difference if I turn it off.
Adding the javascript in code using Page.ClientScript.RegisterStartupScript at some point after the validator has been created does not work either.
If I don't add any validators in code everything works as expected.
I'm aware I can just add the anchor tags manually, but this is a lot of work to update existing validators instead of just tossing in a small script, so I'm hoping to get this to work.
You can use this code to test this:
using System;
using System.Web.UI.WebControls;
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CustomValidator control = new CustomValidator();
control.ID = "cv" + txtName.ClientID;
control.IsValid = false;
control.Text = " ";
control.ValidationGroup = "errorGroup";
control.ErrorMessage = "Error message";
control.ControlToValidate = txtName.ClientID;
Form.Controls.Add(control);
}
}
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:ValidationSummary ID="vsSummary" runat="server" ValidationGroup="errorGroup" ForeColor="Red" HeaderText="Error!" />
</div>
</form>
<script>
$(document).ready(function() {
var validators = Page_Validators; // returns collection of validators on page
$(validators).each(function() {
//get target control and current error validation message from each validator
//[0] is needed when using aspnet 4.5 unobtrusive validation
var validator = $(this)[0];
var errorMsg = validator.errormessage;
var targetControl = validator.controltovalidate;
//make link only if theres a control to target
if (targetControl) {
var errorMsgWithLink = "<a href='#" + targetControl + "' style='color: #FF3232;'> " + errorMsg + "</a>";
//update error message with anchor tag
validator.errormessage = errorMsgWithLink;
}
});
});
</script>
</body>
</html>
If you want you can try implementing your own 'CustomValidationSummary' control by following the same design pattern as mentioned at Reference Source by Microsoft, and modify the render method to include anchor tag to wrap error text, before it is passed into the writer method at line number 462.
I ended up using a extension method, adding the anchor tag in the method
public static void AddValidator(this Page p, string message, string validationGroup, string controlToValidate = "", bool addAnchorTags = true)
{
CustomValidator control = new CustomValidator();
control.ID = "cv" + controlToValidate;
control.IsValid = false;
control.Text = " ";
control.ValidationGroup = validationGroup;
control.ControlToValidate = controlToValidate;
if (addAnchorTags && !string.IsNullOrEmpty(controlToValidate))
{
control.ErrorMessage = "<a href='#" + controlToValidate + "' style='color: #FF3232;'> " + message + "</a>";
}
else
{
control.ErrorMessage = message;
}
p.Validators.Add(control);
}

calling a JavaScript function on Asp.net textBox

Please help! i have been trying to call this function on my Asp.net textbox to format users input while typing.
function format(number) {
var decimalSeparator = ".";
var thousandSeparator = ",";
var result = String(number);
var parts = result.split(decimalSeparator);
if (!parts[1]) {
parts[1] = "00";
}
result = parts[0].split("").reverse().join("");
result = result.replace(/(\d{3}(?!$))/g, "$1" + thousandSeparator);
parts[0] = result.split("").reverse().join("");
return parts.join(decimalSeparator);
}
// i tried using onkeyup, it didnt work
<asp:TextBox ID="txtTransport" runat="server" CssClass="TextBoxes" onKeyup="javaScript: format(this);"></asp:TextBox>
// also i tried using onChange, it didnt work.
<asp:TextBox ID="txtTransport" runat="server" CssClass="TextBoxes" onChange="javaScript:format(this);"></asp:TextBox>
protected void Page_Load(object sender, EventArgs e)
{
txtTransport.Attributes.Add("onKeyup", "javaScript: format(this);");
}
You can do it directly from javascript, not in codebehind !
var el = document.getElementById("<%= txtTransport.ClientID %>");
el.onkeyup = function(e) {
// Do stuff
};
But I think your function is logicaly wrong. Try it anyway. Your ID of a server side control is not exactly the same you write in the code, for get the real ID you can use <%= txtTransport.ClientID %>.

Trouble writing cookie value to form field

Being a Javascript novice I am having some trouble implementing Google's Adwords GCLID tracking on our site. I am following their code examples show here https://support.google.com/adwords/answer/2998031.
You can see the cookie being stored but when trying to retrieve it and populate a hidden form field the result is just blank. I have used other variations but that simply results in "Undefined" as the field value.
Here is the code I'm using
Simplified HTML Form
<form class="signup-form" name="signupform" method="post" action="step2.php">
<input type="hidden" name="gclid" id="gclid" value="" />
</form>
Cookie Write Script
<script type="text/javascript">
function setCookie(a,d,b){var c=new Date;c.setTime(c.getTime()+864E5*b);b=";
expires="+c.toGMTString();document.cookie=a+"="+d+b}function getParam(a) {return(a=RegExp("[?&]"+a+"=([^&]*)").exec(window.location.search))&&decodeURIComponent(a[1].replace(/\+/g," "))}var gclid=getParam("gclid");if(gclid){var gclsrc=getParam("gclsrc");(!gclsrc||-1!==gclsrc.indexOf("aw"))&&setCookie("gclid",gclid,90)};
</script>
Cookie Read Script
<script>
function readCookie(name) {
var n = name + "=";
var cookie = document.cookie.split(';');
for(var i=0;i < cookie.length;i++) {
var c = cookie[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(n) == 0){
return c.substring(n.length,c.length);
}
}
return null;
}
function() {
document.getElementById('gclid').value = readCookie('gclid');
}
</script>
function() {
document.getElementById('gclid').value = readCookie('gclid');
}
this is a function without a name that's never called. try replacing it with only
document.getElementById('gclid').value = readCookie('gclid');
I rewrote your write script, I think your cookie is never set.
function setCookie(a,d,b) {
var c = new Date;
c.setTime(c.getTime()+864E5*b);
b="; expires=" + c.toGMTString();
document.cookie = a + "=" + d + b
}
function getParam(a) {
return(a=RegExp("[?&]"+a+"=([^&]*)").exec(window.location.search))&&decodeURIComponent(a[1].replace(/\+/g," "))
}
var gclid=getParam("gclid");
if(gclid) {
var gclsrc = getParam("gclsrc");
if(!gclsrc||-1 !== gclsrc.indexOf("aw")) {
setCookie("gclid", gclid, 90);
alert("Cookie Set!");
}
}
Working script modified from https://support.google.com/adwords/answer/3285060. I just changed the document.onload to window.onload It seems there was too much going on off screen in the DOM.
<script>
window.onload = function getGclid() {
document.getElementById("gclid").value = (name = new
RegExp('(?:^|;\\s*)gclid=([^;]*)').exec(document.cookie)) ?
name.split(",")[1] : ""; }
</script>

How can I write javascript functions in content page html and how I call that function

I write two javascript functions in content page. Then I take a html textbox and on the onkeypress event I try to call those two functions, but I am running that application and I didn't find any output to help me.
Here I am trying to count number of characters in textbox on keypress event. If I write a javascript function in simple page then it runs successfully but it doesn't run in content page help me.
Here is the code
<%# Page Language="C#" AutoEventWireup="true" MasterPageFile ="~/Site1.Master" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<asp:Content ID="Content1" runat="server"
contentplaceholderid="ContentPlaceHolder1">
<script language ="javascript" type = "text/javascript">
maxL=0;
var bName = navigator.appName;
function taCount(taObj,Cnt,totmsg)
{
objCnt=createObject(Cnt);
objtotmsg = createObject(totmsg);
objVal=taObj.value;
if (objCnt)
{
if(bName == "Netscape")
{
//objCnt.textContent = maxL-objVal.length;}
var totalchar = parseInt((objVal.length - 1) / 160);
objCnt.textContent = maxL + objVal.length;
objtotmsg.textContent = totalchar + 1;
}
//else{objCnt.innerText= maxL -objVal.length;}
else
{
var totalchar = parseInt((objVal.length - 1) / 160);
objCnt.innerText= maxL + objVal.length;
objtotmsg.innerText = totalchar + 1;
}
}
return true;
}
function createObject(objId)
{
if (document.getElementById) return document.getElementById(objId);
else if (document.layers) return eval("document." + objId);
else if (document.all) return eval("document.all." + objId);
else return eval("document." + objId);
}
</script>
<textarea id="TextArea1" onkeyup="return taCount(this,'charcount','totalmsg')" cols="20" rows="10"></textarea>
<asp:Label ID="charcount" runat="server" Text="0"></asp:Label>/<asp:Label ID="totalmsg" runat="server" Text="0"></asp:Label>
</asp:Content>
This is because the IDs get lengthened (their naming containers are pre-pended) when inside a master page, so instead of this:
taCount(this,'charcount','totalmsg')
You'll need this, which gets their actual rendered IDs:
taCount(this,'<%=charcount.ClientID %>','<%=totalmsg.ClientID %>')
If you view source in the browser and search for charcount or totalmsg when rendered in that master page, you'll see what I mean about the IDs, they'll probably look something like this: _ctl00_Content1_charcount.

Categories