I want to call a method hello() in javascript from aspx.cs ( c# ) when a listbox1 item is selected.Using this code to do it but not working
protected void ListBox1_TextChanged(object sender, EventArgs e)
{
ClientManager.RegisterStartupScript(this, GetType(), "whatiskey","hello();", true);
}
function hello() {
alert("hiiiii");
var arr = ["<%=myvalue %>"];
}
Setting "AutoPostBack" property of ListBox to "true" and using Page.ClientScript.RegisterStartupScript(GetType(), "whatiskey", "hello();", true); worked for me
use
Response.Write("<script>hello();</script>");
EDIT
if all you wanna do is call a javascript on selection of an item, you can use onchange attribute as follows -
<asp:ListBox onchange="hello();" ID="ListBox1" runat="server">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
</asp:ListBox>
<script>
function hello() {
alert("hello");
}
</script>
Related
I am using ASP.NET UpdatePanel for partial postback. Somehow after the server side postback (ddl_SelectedIndexChanged), the value set by a Javascript function (lblTotal's value of 100) gets removed. Is there anyway to preserve value set by the Javascript function?
JavaScript:
<script type="text/javascript">
function calculateTotal() {
var lblTotal = document.getElementById("<%= lblTotal.ClientID%>");
lblTotal.innerHTML = "100";
}
</script>
HTML:
<asp:UpdatePanel ID="UpdateGrid" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddl" runat="server" OnTextChanged="ddl_SelectedIndexChanged" AutoPostBack="true" />
<asp:CheckBox ID="chkLevels" runat="server" onclick="calculateTotal()" />
<asp:Label ID="lblTotal" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
C# / Code Behind:
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
// Some code
}
The problem is here is that when you change data with calculateTotal in Javascript, server does not know about changes since you don't post back data to server.
So you need to trigger the postback event with __doPostBack():
Client side:
function calculateTotal() {
var lblTotal = document.getElementById("<%= lblTotal.ClientID%>");
//Calculation
var totalValue = "100";
__doPostBack('chkLevels', totalValue);
}
Page_Load on Server side :
protected void Page_Load(object sender, EventArgs e)
{
if (Request["__EVENTTARGET"] == "chkLevels")
{
var totalValue = Request["__EVENTARGUMENT"];
lblTotal.Text = totalValue;
}
}
See: how to use __doPostBack function in asp.net
It doesn't look like this is possible, but is there any way to pass a javascript variable into the CommandArgument field? I'm trying to pass the facility_id variable so that the code behind can access the value.
Here is my aspx code:
<script type="text/javascript">
var facility_id = 50;
</script>
<asp:Button CssClass="btn btn-primary btn-lg" ID="submitBtn" runat="server" Text="Create EDD" CommandArgument='<% facility_id.Value %>' OnClick="submitBtn_Click" />
As you expect, the CommandArgument is a server-side property of Button server control and you can't assign it from client-side code because it does not render corresponding HTML attribute. However, you can set up a postback from client-side with __doPostBack() function as provided below:
<script>
var facility_id = 50;
$('#something').click(function () {
__doPostBack("<%= submitBtn.UniqueID %>", facility_id);
});
</script>
Code behind
protected void submitBtn_Click(object sender, EventArgs e)
{
// assumed 'facility_id' is an int? or Nullable<int> property,
// make sure the event argument is parseable to integer value
var evArg = int.Parse(Request.Form["__EVENTARGUMENT"]);
facility_id = evArg;
}
If you cannot use __doPostBack() function because it is undefined on the page, then you can handle PreRender event of that page and provide GetPostBackEventReference() method:
protected void Page_PreRender(object sender, EventArgs e)
{
ClientScript.GetPostBackEventReference(submitBtn, string.Empty);
}
I have a Textbox in GridView I want to change the Label.Text if the text in Textbox is changed. But I am not able call javascript function written in .cs page. Is there any mistake in TbUnitCost_TextChanged method.
This is my aspx page
<ItemTemplate>
<asp:TextBox Style="text-align: right" ID="TbUnitCost" runat="server" Width="80px" Text='<%#Bind("Unit_Cost")%>' AutoPostBack="true" OnTextChanged="TbUnitCost_TextChanged" TextMode="Number"></asp:TextBox>
</ItemTemplate>
Code behind Page is as follows
protected void TbUnitCost_TextChanged (object sender, EventArgs e)
{
GridViewRow currentRow = (GridViewRow)((TextBox)sender).Parent.Parent;
int rowNo = currentRow.RowIndex;
string gridName = "GridWorkExpenses";
TextBox tbunitCost = (TextBox)currentRow.FindControl("TbUnitCost");
int row = Convert.ToInt32(tbunitCost.Text);
tbunitCost.Attributes.Add("onchange","javascript:calculateTotalCost('"+rowNo+"','"+gridName+"');");
}
and javascript Function is:
<script type ="text/javascript">
function calculateTotalCost(rowNo, GridName) {
if (GridName== 'GridWorkExpenses') {
var rowscount = document.getElementById('<%=GridWorkExpensesSheet.ClientID%>').rows.length;
return calculateTotalUnitCost("GridWorkExpensesSheet", rowscount,rowNo);
}
}
</script>
Try using this:
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script", "CalculateTotalCost", true);
Describe any further problem (if there is any).
ScriptManager.RegisterStartupScript(this, this.GetType(), "Script", "<script type='text/javascript'>CalculateTotalCost</script>", false);
is another method
This is a very old discussion [1]:Difference between RegisterStartupScript and RegisterClientScriptBlock?
Please refer this too.
hi you must write all of command in the one string
ScriptManager.RegisterClientScriptBlock((sender as Control), GetType(), "jQueryCommand", "$('.MenuLoginLink').hide();$('.MenuUsername').show();$('.MenuUsername').text('" + Currentmember.Mobile + "');$('.MenuExit').show();" +
" $('.btnLoginInFriends').hide();$('#HiddenSession').val('" + int.Parse(Session["CurrentUserID"].ToString()) + "');", true);
I am trying to call a javascript function from onClick event of an asp server button. I have this button and a label in an update panel.
In aspx:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="Button1" runat="server"
style="z-index: 1; left: 49px; top: 119px; position: absolute; height: 26px;" Text="Button"
onclick="Button1_Click"/>
<asp:Label ID="Label1" runat="server" Text="l1"
style="position:absolute; top: 123px; left: 127px;"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, typeof(Button), "me", "me()", true);
}
Javascript in aspx:
<script type="text/javascript">
function me()
{
document.getElementById('<%= Label1.ClientID %>').value="clicked";
}
</script>
All I am trying to do is on button click the label's value should be changed to 'clicked', which isn't happening and no error as well in firebug. Where am I wrong in the me( )?
P.S: I am doing this to learn calling a javascript function from code behind. So any optimizations to the code are also welcome. (I actually have much lot of code to implement in the JS function later so appropriate suggestions please)
As far as I remember the Label control is rendered as a <div> or <span> (can't remember exactly), not a text input field. So you should be setting its innerHTML property not the value:
document.getElementById('<%= Label1.ClientID %>').innerHTML = 'clicked';
or simply do it on the server side instead of registering clientside callbacks:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "clicked";
}
UPDATE:
As requested in the comments section here's how you could pass parameters to the clientside callback from the server:
protected void Button1_Click(object sender, EventArgs e)
{
string param1 = ...
double param2 = ...
int param3 = ...
var serializer = new JavaScriptSerializer();
ScriptManager.RegisterClientScriptBlock(
this,
typeof(Button),
"me",
string.Format("me({0})", serializer.Serialize(new { param1 = param1, param2 = param2, param3 = param3 })),
true
);
}
and your callback:
function me(values) {
// you could use values.param1, values.param2, values.param3, ... here
}
In my form I have a textbox and a calendar along with other controls:
<asp:TextBox ID="TextBox2" runat="server" onfocus="CalOpen()" asp:TextBox>
<asp:Calendar ID="Calendar1" runat="server" style="display:none;"
onselectionchanged="Calendar1_SelectionChanged"></asp:Calendar>
<script type="text/javascript">
function CalOpen()
{
var cal = document.getElementById('<%=Calendar1.ClientID%>');
cal.style.display='block';
}
</script>
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
TextBox2.Text = Calendar1.SelectedDate.ToLongDateString();
Calendar1.Visible = false;
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Calendar1.Visible = true;
}
For the first time it worked fine,
but, second time when I click TextBox2, that is, after selecting date for the first time the
browser is throwing error "object required".
I am unable to know where I went wrong.
Please help me in making my code correct.
When you write Calendar1.Visible = false; in server-side code, it doesn't render the calendar at all. Therefore, there is no calendar element for the Javascript to show.
Instead, you should make a CSS class that applies display: none to the calendar, and set the CssClass property to that class on the server.
For example:
<style type="text/css">
.Hidden {
display: none;
}
</style>
<asp:Calendar ID="Calendar1" runat="server" CssClass="Hidden"
onselectionchanged="Calendar1_SelectionChanged"></asp:Calendar>
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
TextBox2.Text = Calendar1.SelectedDate.ToLongDateString();
Calendar1.CssClass = "Hidden";
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Calendar1.CssClass = "";
}