I have referenced my javascript in my page as follows
<script src="JScript1.js" type="text/javascript"></script>
These are my function inside that script file
function multiplication(txtQuantity) {
var weight = document.getElementById(txtQuantity).value;
}
function f(sender, args) {
args.IsValid = false;
var gridview = document.getElementById("<%=Gridview1.ClientID%>");
var txt = gridview.getElementsByTagName("textarea");
for (i = 0; i < txt.length; i++) {
if (txt[i].id.indexOf("TextBox1") != -1) {
if (txt[i].value == '') {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
}
}
function f1(sender, args) {
args.IsValid = false;
var gridview = document.getElementById("<%=Gridview1.ClientID%>");
var txt = gridview.getElementsByTagName("textarea");
for (i = 0; i < txt.length; i++) {
if (txt[i].id.indexOf("TextBox2") != -1) {
if (txt[i].value == '') {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
}
}
I would like to call these function from my code behind and also I would like to assign the function to custom validator
I tried some thing as follows but not working
<asp:CustomValidator ID="custValCountry" runat="server" ValidationGroup="Country"
ValidateEmptyText="true" ControlToValidate="TextBox1" ClientValidationFunction="javascript:f"
ErrorMessage="Other is required"></asp:CustomValidator>
Also my under my RowDataBound event I write as follows this is also not working
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txt = (TextBox)e.Row.FindControl("TextBox1");
Page.ClientScript.RegisterClientScriptBlock(txt.GetType(), "onBlur", "multiplication('" + txt.ClientID + "')");
//Page.ClientScript.RegisterClientScriptBlock(, "Script", "alert('Records Successfuly Saved!');", true);
// txt.Attributes.Add("onBlur", "return javascript:multiplication('" + txt.ClientID + "');");
//TextBox txt1 = (TextBox)e.Row.FindControl("TextBox2");
txt1.Attributes.Add("onBlur", "return javascript:multiplication('" + txt1.ClientID + "');");
}
}
Can some one help me
Static JavaScript files do not get fed through ASP.NET normally, so this line will not work:
var gridview = document.getElementById("<%=Gridview1.ClientID%>");
Use a fixed ID for the grid and specify it directly:
var gridview = document.getElementById('my-grid');
<asp:GridView ID="my-grid" ClientIDMode="Static" runat="server" ...>
Or come up with some other way of finding the ID.
Also note that this function is next to worthless:
function multiplication(txtQuantity) {
var weight = document.getElementById(txtQuantity).value;
}
You get the weight then do nothing with it?
You need to realize that your javascript functions are running in the client's browser, not on your server where your code behind is running. If you need to call the functions from your code behind, you will need to create equivalent functions in your code behind.
Related
I am quite new to ASP and I have been stuck on an issue for about a week. The issue is probably something to do with the Asp Page Life Cycle but I am unable to find how this can be resolved. The issue is that skipto(..) is never called when I click the LinkButton (that were created on first Page Load), which means the LinkButtons are not rendered.
Sample Code below:
// Code Behind
protected void Page_Load(object sender, EventArgs e)
{
loadData();
if (!Page.IsPostBack)
{
skiptof();
}
}
public void loadData() {
// Loads from database
}
public void skipto(object sender, EventArgs e)
{
LinkButton btn = sender as LinkButton;
if (btn != null)
{
if (btn.CommandArgument != null && btn.CommandArgument != "0")
{
int currPage = 1;
int.TryParse(btn.CommandArgument, out currPage);
skiptof(currPage);
}
}
}
public void skiptof(int currPage = 1)
{
int lastPage = // calculate from LoadData()
string pageDisabled = "";
// pages
HtmlGenericControl ul = new HtmlGenericControl("ul");
while (pageCount <= lastPage)
{
// Disable the current page
pageDisabled = pageCount == currPage ? " class=\"disabled\"" : "";
HtmlGenericControl pagesli = new HtmlGenericControl("li");
if (pageDisabled != "")
{
pagesli.Attributes.Add("class", "disabled");
}
LinkButton pagesPageLink = new LinkButton();
pagesPageLink.Click += new EventHandler(skipto);
pagesPageLink.CommandArgument = pageCount.ToString();
pagesPageLink.Text = pageCount.ToString();
pagesli.Controls.Add(pagesPageLink);
ul.Controls.Add(pagesli);
pageCount += 1;
}
pagination.Controls.Add(ul);
}
// page
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
<asp:UpdatePanel runat="server" id="UpdatePanel" UpdateMode="Conditional">
<ContentTemplate>
<div id="details" runat="server"></div>
<div class="pagination text-center" id="pagination" runat="server"></div>
</ContentTemplate>
</asp:UpdatePanel>
Your problem is:
You didn't bind the data again on postback, I've modified your code a little bit, there are several problems:
in the method skipof:
public void skiptof(int currPage = 1) {
//Clear the controls here then add them again
pagination.Controls.Clear();
int lastPage = // calculate from LoadData()
string pageDisabled = "";
HtmlGenericControl ul = new HtmlGenericControl("ul");
while (pageCount <= lastPage) {
// Disable the current page
pageDisabled = pageCount == currPage ? " class=\"disabled\"" : "";
HtmlGenericControl pagesli = new HtmlGenericControl("li");
if (pageDisabled != "") {
pagesli.Attributes.Add("class", "disabled");
}
LinkButton pagesPageLink = new LinkButton();
// you can directly assign the method to be called here, there is no need to create a new EventHandler
pagesPageLink.Click += PagesPageLink_Click;
pagesPageLink.CommandArgument = pageCount.ToString();
pagesPageLink.Text = pageCount.ToString();
pagesli.Controls.Add(pagesPageLink);
ul.Controls.Add(pagesli);
pageCount += 1;
}
pagination.Controls.Add(ul);
}
You didn't bind the data again in postback, so I modified it:
Page Load:
protected void Page_Load(object sender, EventArgs e) {
//Remove the Page.IsPostBack checking
skiptof();
}
Please take note that the controls you added dynamically will be cleared and you have to add it again on postback to avoid data lost.
Then you'll be able to get the value on PagesPageLink_Click event:
The whole sample is here:
http://pastie.org/10503291
am using meta builder checked listbox and their selected index changed working fine in local.but not working on server side. please help me to fix this error. My partial code is here..
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (ListBox1.Items.Count > 0)
{
for (int i = 0; i <= ListBox1.Items.Count; i++)
{
if (ListBox1.Items[i].Selected == true)
{
lblempid.Text = Convert.ToString(ListBox1.Items[i].Text.Substring(0, 8));
lblempname.Text = Convert.ToString(ListBox1.Items[i].Text.Substring(9));
DataSet5TableAdapters.sp_GetallpayperiodTableAdapter TA = new DataSet5TableAdapters.sp_GetallpayperiodTableAdapter();
DataSet5.sp_GetallpayperiodDataTable DS = TA.GetData();
if (DS.Rows.Count > 0)
{
fromdate = Convert.ToString(DS.Rows[DS.Rows.Count - 1]["fldstartdate"]);
todate = Convert.ToString(DS.Rows[DS.Rows.Count - 1]["fldtodate"]);
status = Convert.ToString(DS.Rows[DS.Rows.Count - 1]["fldstatus"]);
if (status == "OPEN")
{
lblfromdate.Text = Convert.ToString(Convert.ToDateTime(fromdate).ToShortDateString());
lbltodate.Text = Convert.ToString(Convert.ToDateTime(todate).ToShortDateString());
}
}
}
}
}
}
catch (Exception e1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "onload", "<script language='javascript'>alert('" + e1.Message + "');</script>", false);
}
Design code:
<%# Register Assembly="MetaBuilders.WebControls" Namespace="MetaBuilders.WebControls"
TagPrefix="mb" %>
<mb:CheckedListBox ID="ListBox1" runat="server" CssClass="textbox" Width="250px"
Height="515px" AutoPostBack="True" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
</mb:CheckedListBox>
please check if the auto post back is true in your aspx code:
Example:
<asp:DropDownList ID="ddlForecastOption" runat="server"
onselectedindexchanged="ddlForecastOption_SelectedIndexChanged"
AutoPostBack="true">
I have searched how to register a Javascript in the code behind file .cs but still have not understand it and what I have tried does not fire the Javascript.
How can I fire an existing javascript function within the
protected void Page_Load(object sender, EventArgs e)
{
}
I have tried
Page.ClientScript.RegisterStartupScript(Type.GetType, "script", "return myFunction()");
But it says that it has invalid arguments? and a bunch of exceptions when I hover the red underline.
Thank you for your help.
Function
function myFunction() {
var combo = $find("<%= myClients.ClientID %>");
//prevent second combo from closing
cancelDropDownClosing = true;
//holds the text of all checked items
var text = "";
//holds the values of all checked items
var values = "";
//get the collection of all items
var items = combo.get_items();
//enumerate all items
for (var i = 0; i < items.get_count(); i++) {
var item = items.getItem(i);
//get the checkbox element of the current item
var chk1 = $get(combo.get_id() + "_i" + i + "_chk1");
if (chk1.checked) {
text += item.get_text() + ",";
values += item.get_value() + ",";
}
}
//remove the last comma from the string
text = removeLastComma(text);
values = removeLastComma(values);
if (text.length > 0) {
//set the text of the combobox
combo.set_text(text);
}
else {
//all checkboxes are unchecked
//so reset the controls
combo.set_text("");
}
}
GetType is a method. Also, your script should be wrapped in script tags. Try this:
Page.ClientScript.RegisterStartupScript(this.GetType(),
"script", "<script>myFunction();</script>");
Try this instead:
Page.ClientScript.RegisterStartupScript(typeof(string), "script", "return myFunction()");
You cannot have a return statement outside a function. Try this hope it helps you provide the function "myFunction" exists in memory before it gets called.
Page.ClientScript.RegisterStartupScript(Type.GetType(), "script", "myFunction()", true);
I have a gridview in an update panel with the following code to select a row, this in turn updates another updatepanel with details from the form record.
protected void gvMainGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Make the entire row clickable to select this record
//Uses javascript to post page back
e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.Attributes.Add("onclick", ClientScript.GetPostBackClientHyperlink(this.gvMainGrid, "Select$" + e.Row.RowIndex));
}
}
I am manually binding the gridview from a database and don't want to rebind the grid just to highlight the row, but I can't seem to add any javascript to the onclick event, it seems to either show the GetPostBackClientHyperlink or the row highlight javascript.
How to highlight gridview when row is selected
for this you have to write this code in your code behind file in OnRowCreated event or your can also write this code in OnRowDataBound event of grid...
protected void ctlGridView_OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onclick", "onGridViewRowSelected('" + e.Row.RowIndex.ToString() + "')");
}
}
and add this one script
<script language="javascript" type="text/javascript">
var gridViewCtlId = '<%=ctlGridView.ClientID%>';
var gridViewCtl = null;
var curSelRow = null;
function getGridViewControl()
{
if (null == gridViewCtl)
{
gridViewCtl = document.getElementById(gridViewCtlId);
}
}
function onGridViewRowSelected(rowIdx)
{
var selRow = getSelectedRow(rowIdx);
if (curSelRow != null)
{
curSelRow.style.backgroundColor = '#ffffff';
}
if (null != selRow)
{
curSelRow = selRow;
curSelRow.style.backgroundColor = '#ababab';
}
}
function getSelectedRow(rowIdx)
{
getGridViewControl();
if (null != gridViewCtl)
{
return gridViewCtl.rows[rowIdx];
}
return null;
}
</script>
and it will highlight the selected row..
I was struggling to add both on click events to the row databound:
e.Row.Attributes.Add("onclick", ClientScript.GetPostBackClientHyperlink(this.gvMainGrid, "Select$" + e.Row.RowIndex));
e.Row.Attributes.Add("onclick", "onGridViewRowSelected('" + e.Row.RowIndex.ToString() + "')");
Appending the PostBack select after the row highlight method with ';' seems to have worked.
e.Row.Attributes.Add("onclick", "onGridViewRowSelected('" + e.Row.RowIndex.ToString() + "');" + ClientScript.GetPostBackClientHyperlink(this.gvMainGrid, "Select$" + e.Row.RowIndex));
Firstly, you can't apply text-decoration to a <tr>... or a <td> for that matter. You need to apply it to the elements inside.
Here are a couple adjustments you can try-
e.Row.Attributes.Add("onmouseover", "this.style.cursor='hand';";
e.Row.Attributes.Add("onclick", ClientScript.GetPostBackClientHyperlink(this.gvMainGrid.ClientId, "Select$" + e.Row.RowIndex));
The 1st works for me in code. Didn't have anything handy to test the 2nd.
I have a page where a user can either select a vendor via dropdown or enter a vendor number via textbox. One or the other must have a value. I can do this in javascript easily but how can I do this using a custom validator provided by ajax all on the client side?
Edited
Protected Sub ImageButton1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click
If Page.IsValid Then
//save stuff
End If
End Sub
Sub ServerValidation(ByVal source As Object, ByVal args As ServerValidateEventArgs) Handles ValidPage.ServerValidate
Try
' Test whether the value entered into the text box is even.
Dim num As Integer = Integer.Parse(args.Value)
args.IsValid = ((num Mod 2) = 0)
Catch ex As Exception
args.IsValid = False
End Try
End Sub
Protected Sub ValidPage_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs)
Try
args.IsValid = (Not String.IsNullOrEmpty(Me.txtVendnum.Text) OrElse Me.DropDownList1.SelectedIndex <> 0)
Catch e As Exception
DirectCast(source, CustomValidator).ErrorMessage = "You must Choose a Vendor"
args.IsValid = False
End Try
End Sub
<script type="text/javascript" language="javascript" >
function ClientValidate(sender, args) {
// Get Both form fields
var ddlvalue = document.getElementById('<%=DropDownList1.ClientID%>');
var txtValue = document.getElementById('<%=txtVendnum.ClientID %>');
// do you client side check to make sure they have something
if (txtValue.value == '' && ddlvalue.value == '0') {
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" ValidationGroup="Save" DataTextField="vmvnnm" DataValueField="vmvend" >
</asp:DropDownList>
<asp:TextBox ID="txtVendnum" ValidationGroup="Save" runat="server"></asp:TextBox><br />
<asp:CustomValidator ID="ValidPage" ValidationGroup="Save" runat="server" ClientValidationFunction="ClientValidate" ErrorMessage="CustomValidator"
SetFocusOnError="True" ControlToValidate="txtVendnum" EnableClientScript="true" Display="Static" OnServerValidate = "ServerValidation" ></asp:CustomValidator>
//other stuff. A different validator group, html editor, etc
<td>
<asp:ImageButton ID="ImageButton1" CausesValidation = "true" ValidationGroup="Save" OnClick="ImageButton1_Click" runat="server" ImageUrl="../images/bttnSave.gif" />
</td>
<asp:CustomValidator ID="ValidPage" runat="server"
EnableClientScript="true"
ClientValidationFunction="My.util.VendnumCheck"
OnServerValidate="ValidPage_ServerValidate"
ControlToValidate="txtVendnum"
ErrorMessage="You must Choose a Vendor"
SetFocusOnError="True"
ValidationGroup="Save">
</asp:CustomValidator>
ClientValidationFunction="My.util.VendnumCheck"
You should also be doing Server Side validation!
protected void ValidPage_ServerValidate(object source, ServerValidateEventArgs args)
{
try
{
args.IsValid = (!string.IsNullOrEmpty(this.txtVendnum.Text) || this.DropDownList1.SelectedIndex != 0);
}
catch (Exception e)
{
((CustomValidator)source).ErrorMessage = "You must Choose a Vendor";
args.IsValid = false;
}
}
protected void Button_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//do work
}
}
JS:
My.util.VendnumCheck = function(sender, args) {
try {
// Get Both form fields
var ddlvalue = document.getElementById("<%=this.DropDownList1.ClientID %>");
var txtValue = document.getElementById("<%=this.txtVendnum.ClientID %>").value;
// do you client side check to make sure they have something
if ( txtValue.length < 1 && ddlvalue.selectedIndex != 0)
args.IsValid = false;
args.IsValid = true;
}
catch (ex) {
My.logError(ex);
args.IsValid = false;
}
}
try having this JS method called on Blur of the text box, see if it picks up the validator...
My.util.callMyValidators = function() {
// Clean Up Infragistics Ids
var cleanid = this.id.replace(/^igtxt/i, "");
if (Page_Validators == null) {
alert("My.util.callMyValidators when Page_Validators is null");
}
var found = 0;
for (var i = 0; i < Page_Validators.length; i++) {
if (Page_Validators[i].controltovalidate === cleanid) {
found++;
ValidatorValidate(Page_Validators[i]);
}
}
if (found === 0) {
alert("My.util.callMyValidators did find any matching validators for " + cleanid);
}
}
You need to set the ClientValidationFunction property of your custom validator to the name of a javascript function that will exist on the page.
The function needs to take in two arguments, one of which is the "args" argument which you will set to be valid or not. An example based on the MSDN page for CustomValidator:
function ClientValidate(source, args)
{
if (myTextBox.Value == "" && myDropDown.Value == "" )
{
args.IsValid=false;
}
else {args.IsValid=true};
}