HI All,
I have created an ASP.Net form that has 2 labels, 2 textboxes & 2 buttons.
I want to pass the values in ASP.Net textboxes to JavaScript function and trigger is from code behind.
I have successfully triggered the JavaScript function from code behind using the below statement.
protected void btnOK_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, GetType(), "MyKey", "myFunction();", true);
}
But when I tried to pass the values it didn't give me an output.
<script type ="text/javascript" >
function myFunction() {
var vUserName = document.getElementById("txtUserName").value;
var vPassword = document.getElementById("txtPassword").value;
var vFullInfo = vUserName + vPassword;
alert(vFullInfo);
}
</script>
What I have tried:
Below is the full source code for the total solution.
Form01
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="frmStudInfo.aspx.cs" Inherits="WebApplication01.frmStudInfo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>First ASP.Net Application</title>
<script type ="text/javascript" >
function myFunction() {
var vUserName = document.getElementById("txtUserName").value;
var vPassword = document.getElementById("txtPassword").value;
var vFullInfo = vUserName + vPassword;
alert(vFullInfo);
}
</script>
</head>
<body>
<form id="form1" runat="server" method="post">
<asp:Label ID="Label1" runat="server" Text="User Name"></asp:Label>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="Password"></asp:Label>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" />
<asp:Button ID="btnOK" runat="server" OnClick="btnOK_Click" Text="OK" />
</form>
</body>
</html>
Code Behind Form 01
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication01
{
public partial class frmStudInfo : System.Web.UI.Page
{
private string strUserName;
private string strPassword;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnOK_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, GetType(), "MyKey", "myFunction();", true);
}
}
}
I checked the code and find out the JavaScript function i.e. MyFunction() does not capture the values from the form. So that the issue is at the passing values from the form to the JS function.
Could someone please explain what whould have gone wrong?
Thanks,
Chiranthaka