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 %>.
Related
The problem here is sometimes it will not trigger RadGrid1_BatchEditCommand. Please help.
I have codes below at javascript:
var grid = $find("<%=RadGrid1.ClientID %>");
var batchManager1 = grid.get_batchEditingManager();
var hasChanges = batchManager1.hasChanges(grid.get_masterTableView());
if(hasChanges) {
grid.get_batchEditingManager().saveChanges(grid.get_masterTableView());
}
else{
args.set_cancel(true);`
window.close();
}
I have code below at code behind:
protected void RadGrid1_BatchEditCommand(object sender, GridBatchEditingEventArgs e)
{
enter code here
}
I do this in my case.
var grid = $find("<%=RadGrid1.ClientID %>");
var batchManager1 = grid.get_batchEditingManager();
grid.get_batchEditingManager().saveChanges(grid.get_masterTableView());
I'm using ASP to look for the selected value in a dropdown box. The dropdown box choices are generated at load time. Here is the JavaScript for that:
function CreateDepartmentDropdown(data) {
var dropdown = document.getElementById("department_dropdown");
for (var i = 0; i < data.length; i++) {
var array = data[i].split(',');
var option = document.createElement("option");
option.value = array[0];
option.innerHTML = array[1];
dropdown.add(option);
}
}
And it looks like this:
Looks fine to me. Then I checked the HTML out too just to be sure:
That looks great too. Now here is where the issue comes up. When I press submit this delegate fires in C# (still only testing while making this):
void Activity_Submit_Click(object sender, EventArgs e)
{
int fye = Int32.Parse(fye_dropdown.Value);
String activity_name = activity_name_field.Value;
String activity_responsible = responsible_field.Value;
int department = Int32.Parse(department_dropdown.Value);
String activity_start = datepicker_start.Value;
String activity_end = datepicker_end.Value;
}
And when I debug this it stops at department saying that it's malformed. Looking at department_dropdown.Value in the immediate window turns up an empty string and the dropdown itself has 0 children.
Why would this return an empty response when the list is clearly there? How would I go about fixing this?
The client-side items won't get posted back to the server like this.
The easiest way is to Serialize the array as Json, put it in a hidden input element's value :
In your markup:
<asp:HiddenField runat="Server" ID="department_dropdown_items" cssclass="department_dropdown_items" />
<asp:HiddenField runat="Server" ID="department_dropdown_selected" cssclass="department_dropdown_selected" />
Your Javascript:
function CreateDepartmentDropdown(data) {
var dropdown = document.getElementById("department_dropdown");
for (var i = 0; i < data.length; i++) {
var array = data[i].split(',');
var option = document.createElement("option");
option.value = array[0];
option.innerHTML = array[1];
dropdown.add(option);
}
$(".department_dropdown_items").text(JSON.Stringify(data));
}
$(document).ready(function() {
$("form").submit(function(e) {
$(".department_dropdown_selected").text( $("#department_dropdown").value);
});
});
then use it in the code behind:
void Activity_Submit_Click(object sender, EventArgs e)
{
string[] data = new JavascriptSerializer().Deserialize<string[]>(department_dropdown_items.Value);
string selectedValue = department_dropdown_selected.Value;
int fye = Int32.Parse(fye_dropdown.Value);
String activity_name = activity_name_field.Value;
String activity_responsible = responsible_field.Value;
int department = Int32.Parse(department_dropdown.Value);
String activity_start = datepicker_start.Value;
String activity_end = datepicker_end.Value;
}
The code is not tested. Tell me if it's not working :)
So I ended up doing the following:
Make a Hidden asp element called department_dropdown_selected_value
Then in a Script tag I made the following function:
.
function GetDepartmentDropdownValue(sel) {
var hidden_field = document.getElementById('department_dropdown_selected_value');
hidden_field.value = sel.value;
}
Then in my HTML I did this: <select class="form-control" id="department_dropdown" onchange="GetDepartmentDropdownValue(this)">
Then I can just simply do this in C#: int department = Int32.Parse(department_dropdown_selected_value.Value);
I am assigning a value to asp textbox in javascript as follows:
var tempStorytxt = document.getElementById("<%=txtStory.ClientID%>");
tempStorytxt.Value = TempValue;
alert(tempStorytxt.Value);
but when I access in codebehind as follows there is nothing in txtStory
int StoryId = int.Parse(txtStory.Text);
Use small V as txtStorytxt.value not txtStorytxt.Value
Try this one:
document.getElementById("<%= txtStory.ClientID%>").value = TempValue;
try this;
<asp:Button ID="btnTest" runat="server" OnClientClick="setVal()" OnClick="btnTest_Click" Text="Test" />
your js function;
function setVal()
{
var tempStorytxt = document.getElementById("<%=txtStory.ClientID%>");
tempStorytxt.setAttribute("value", tempValue);
alert(tempStorytxt.getAttribute("value"));
}
and in button click event;
int StoryId = int.Parse(txtStory.Text);
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);
}
}
I have an Asp server control button for which I have onClick for processing code in code behind and onClientClick to process javascript code. The codes are:
Update: As per Icarus solution, updated codes :
Button source:
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
style="z-index: 1; left: 648px; top: 202px; position: absolute"
Text="Show route" OnClientClick="droute(); return false" />
<asp:HiddenField ID="hdncroute" runat="server" />
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
using (con = new MySqlConnection("server=localhost; uid=root;password=as64ws;database=Gmaps"))
da = new MySqlDataAdapter("select * from routes where uid='" + Session["uname"].ToString() + "'", con);
da.Fill(ds, "mroute");
foreach (DataRow r in ds.Tables[0].Rows)
{
uroute.Add(r["latlng"].ToString());
}
croute = new string[uroute.Count];
croute = uroute.ToArray();
hdncroute.Value = string.Join("&", croute);
}
Javascript function:
function droute()
{
var route=[];
var temp;
temp = eval(document.getElementById('<%= hdncroute.ClientID %>').value);
route= temp.split('&');
//Polyline icon n line settings
var iconsetngs= {path:google.maps.SymbolPath.FORWARD_CLOSED_ARROW, fillColor:'#FF0000'};
var polylineoptns= {strokeColor:'#3333FF',strokeOpacity:0.8,strokeWeight:3,map:map,icons:[{icon:iconsetngs,offset:'100%'}]};
polyline= new google.maps.Polyline(polylineoptns);
//Loop to add locations and draw line
var path= polyline.getPath();
for(var i=0;i<route.length;i++)
{
var marker= new google.maps.Marker({position:route[i],map:map});
path.push(route[i]);
google.maps.event.addListener(marker,'click',showiwindow);
}
//Event Listener's
function showiwindow(event)
{
iwindow.setContent("<b>Coordinates are:</b><br/>Latitude:"+event.latLng.lat()+"<br/>Longitude:"+event.latLng.lng());
iwindow.open(map,this);
}
}
I know that writing return false for javascript function will avoid refresh, and also onClick has void return type. But still my page reloads on button click.
You have an error here:
route = document.getElementById('<%= croute %>').value;
It should be:
route = document.getElementById('<%= croute.ClientID %>').value;
Update:
Markup - declare a hidden element in the page
<asp:hiddenfield id="hdnCroute" runat="server" />
//code behind
int [] croute = ...
hdnCroute.Value = "["+string.Join(",",croute)+"]";
Now Javascipt:
//now you have an array back in javascript
var route= eval(document.getElementById('<%= hdnCroute.ClientID %>').value);
why the page reload?
OnClientClick="droute(); return false"
at inner of browser like this:
button.onclick = function(){
droute();
return false
};
while droute is going wrong,so,return false doesn't work.