Hello, I have a doubt about javascript. When designing web based system, usually we used javascript to validate the form. It works fine in IE browser. However, all the validation does not work when tested on firefox browser.

Why and what is the problem? How to solve it so that the application can be used in any browser?

Thank you.

Recommended Answers

All 9 Replies

You must be using browser specific features. IE is notorious in making your code run even when it is not correct. Paste the code and we will try to help you out. The only advice we can give you is to develop for Firefox so the possibility of the code working on other browsers is more plus you get a nice Error Console and tools like FireBug.

Here is part of the coding using C#. This is one of the module for ASP.NET web based system. Sorry if the coding are messy. The validation are mostly done using .NET validator in which is said to be javascript. Please correct me if I'm wrong.

// Interface
<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="iso-8859-1" Inherits="AddShippingRates" Src="AddShippingRates.cs"%>
<%@ Register TagPrefix="uc1" TagName="InnovaBanner" Src="InnovaBanner.ascx" %>
<%@ Register TagPrefix="uc1" TagName="AdminLinks" Src="AdminLinks.ascx" %>
<%@ Register TagPrefix="uc1" TagName="copyrightfooter" Src="copyrightfooter.ascx" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "[URL]http://www.w3.org/TR/html4/loose.dtd[/URL]">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>InnovaCraft-AddShippingRates</title>
<link href="StyleAdmin.css" type=text/css rel=stylesheet>
</head>
<body>
<table width="806" height="589" border="1" align="center" cellpadding="0" cellspacing="0" bordercolor="#993333">
  <tr>
    <td width="817" height="16" bgcolor="#993333">&nbsp;</td>
  </tr>
  <tr>
    <td height="16" bgcolor="#993333" align="center"><uc1:InnovaBanner id="InnovaBanner1" runat="server"></uc1:InnovaBanner></td>
  </tr>
  <tr>
    <td height="16" bgcolor="#FFFFFF"><uc1:AdminLinks id="AdminLink1" runat="server"></uc1:AdminLinks></td>
  </tr>
  <tr>
    <td height="16" bgcolor="#993333"><span class="adminManagementTitle">Add Shipping Rates </span></td>
  </tr>
  <tr>
    <td height="16" bgcolor="#FFFFFF"><span class="welcome">Welcome&nbsp;&nbsp;&nbsp;
        <asp:Label ID="admin" runat="server" />        </span></td>
  </tr>
  <tr>
    <td height="600" valign="top" bgcolor="#FFFFFF"><form name="form1" method="post" runat="server">
      <table width="800" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <td valign="top"><table width="792" border="0" align="left" cellpadding="0" cellspacing="0">
            <tr>
              <td colspan="6"><asp:Label ID="Message" Visible="false" runat="server" CssClass="adminContent"/></td>
            </tr>
            <tr>
              <td width="146"><span class="adminContent">Shipping Rate ID</span></td>
              <td colspan="5"><asp:TextBox ID="sidtxt" runat="server" Columns="5" ReadOnly="true" TextMode="SingleLine" /></td>
            </tr>
            <tr>
              <td><span class="adminContent">Country</span></td>
              <td colspan="5"><asp:TextBox ID="countrytxt" runat="server" TextMode="SingleLine" /></td>
            </tr>
            <tr>
              <td><span class="adminContent">Shipping Rate </span></td>
              <td colspan="5"><asp:TextBox ID="ratetxt" runat="server" TextMode="SingleLine" /></td>
            </tr>
            <tr>
              <td colspan="6">&nbsp;</td>
            </tr>
            <tr>
              <td>&nbsp;</td>
              <td colspan="2">&nbsp;</td>
              <td width="78"><asp:Button ID="add" Text="Add" Width="60" runat="server" /></td>
              <td width="77"><asp:Button ID="reset" Text="Reset" runat="server" Width="60" CausesValidation="false" /></td>
              <td width="250"><asp:Button ID="cancel" Text="Cancel" runat="server" CausesValidation="false" /></td>
            </tr>
            <tr>
              <td colspan="6">&nbsp;</td>
            </tr>
          </table>
            <p>&nbsp;</p>
            <p>&nbsp;</p>
            <p>&nbsp;</p>
            <p>&nbsp;</p>
            </td>
        </tr>
        <tr>
          <td><table width="793" border="0" align="left" cellspacing="0">
            <tr>
              <td colspan="2"><asp:DataGrid AllowPaging="true" DataKeyField="ShippingRateID" ID="Shippingdg" runat="server" AutoGenerateColumns="false" OnPageIndexChanged="Paging" PageSize="5" Width="800" AlternatingItemStyle-CssClass="alternateRow">
                  <columns>
                  <asp:BoundColumn DataField="ShippingRateID" HeaderText="Shipping Rate ID" ReadOnly="true">
                    <headerstyle CssClass="dgheaderStyle"></headerstyle>
                    <itemstyle CssClass="dgitemStyle"></itemstyle>
                  </asp:BoundColumn>
                  <asp:BoundColumn DataField="DeliveryCountry" HeaderText="Country Destination">
                    <headerstyle CssClass="dgheaderStyle"></headerstyle>
                    <itemstyle CssClass="dgitemStyle"></itemstyle>
                  </asp:BoundColumn>
                  <asp:BoundColumn DataField="ShippingRates" HeaderText="Shipping Rates(USD)">
                    <headerstyle CssClass="dgheaderStyle"></headerstyle>
                    <itemstyle CssClass="dgitemStyle"></itemstyle>
                  </asp:BoundColumn>
                  <asp:TemplateColumn HeaderText="Edit">
                    <headerstyle CssClass="dgheaderStyle"></headerstyle>
                    <itemstyle CssClass="dgitemStyle"></itemstyle>
                    <itemtemplate>
                      <asp:HyperLink runat="server" Width="20" NavigateUrl='<%# "EditShippingRates.aspx?Shipping_ID=" + DataBinder.Eval(Container.DataItem, "ShippingRateID") %>' >Edit</asp:HyperLink>
                    </itemtemplate>
                  </asp:TemplateColumn>
                  <asp:TemplateColumn HeaderText="Delete">
                    <headerstyle CssClass="dgheaderStyle"></headerstyle>
                    <itemstyle CssClass="dgitemStyle"></itemstyle>
                    <itemtemplate>
                      <asp:CheckBox ID="delcb" runat="server"></asp:CheckBox>
                    </itemtemplate>
                  </asp:TemplateColumn>
                  </columns>
                  <pagerstyle HorizontalAlign="Right" Mode="NumericPages" CssClass="dgFooter"></pagerstyle>
              </asp:DataGrid></td>
            </tr>
            <tr>
              <td height="26" colspan="2">&nbsp;</td>
            </tr>
            <tr>
              <td>&nbsp;</td>
              <td><asp:Button ID="delete" Text="Delete Checked Item(s)" runat="server" CausesValidation="false" /></td>
            </tr>
            <tr>
              <td colspan="2">&nbsp;</td>
            </tr>
            <tr>
              <td><asp:RequiredFieldValidator ControlToValidate="countrytxt" Display="None" ErrorMessage="Country must not be empty" ID="empty1" runat="server" />          
                  <asp:RequiredFieldValidator ControlToValidate="ratetxt" Display="None" ErrorMessage="Shipping Rates must not be empty" ID="empty2" runat="server" />            
                  <asp:RegularExpressionValidator ControlToValidate="countrytxt" Display="None" ErrorMessage="Country must be alphabets" ID="v1" runat="server" ValidationExpression="[a-zA-Z]*" />            
                  <asp:RegularExpressionValidator ControlToValidate="ratetxt" Display="None" ErrorMessage="Rate must be in price format" ID="v2" runat="server" ValidationExpression="[0-9][0-9]*(\.+\d{2})?" />            
                &nbsp;</td>
              <td>&nbsp;</td>
            </tr>
            <tr>
              <td width="639"><asp:ValidationSummary DisplayMode="BulletList" HeaderText="ERROR:" ID="summary" runat="server" ShowMessageBox="true" ShowSummary="false"/>          
                &nbsp;</td>
              <td width="150">&nbsp;</td>
            </tr>
          </table>
            <p>&nbsp;</p>
            <p>&nbsp;</p>
            <p>&nbsp;</p>
            <p>&nbsp;</p>
            <p>&nbsp;</p>
            <p>&nbsp;</p>
            <p>&nbsp;</p>
            <p>&nbsp;</p>
            <p></p></td>
        </tr>
      </table>
    </form>
    </td>
  </tr>
  <tr>
    <td height="16" bgcolor="#FFFFFF"><uc1:copyrightfooter id="Copyrightfooter1" runat="server"></uc1:copyrightfooter></td>
  </tr>
</table>
</body>
</html>

// Coding for the logic
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
public class AddShippingRates : Page
{
 protected Label Message;
 protected Button add;
 protected DataGrid Shippingdg;
 protected TextBox sidtxt;
 protected TextBox ratetxt;
 protected TextBox countrytxt;
 protected Button reset;
 protected Button cancel;
 protected Button delete;
 protected Label admin;
 SqlConnection con;
 string db = ConfigurationSettings.AppSettings["constring"].ToString();
 #region Web Form Designer generated code
 override protected void OnInit(EventArgs e)
 {
  //
  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
  //
  InitializeComponent();
  base.OnInit(e);
 }
  
 /// <summary>
 /// Required method for Designer support - do not modify
 /// the contents of this method with the code editor.
 /// </summary>
 private void InitializeComponent()
 {
  this.delete.Click += new System.EventHandler(this.Delete_Click);
  this.reset.Click += new System.EventHandler(this.Reset_Click);
  this.add.Click += new System.EventHandler(this.Add_Click);
  this.cancel.Click += new System.EventHandler(this.Cancel_Click);
 }
 #endregion
 private void Page_Load(object sender, System.EventArgs e)
 {
  // Disable caching in user's web browser works both in IE and Firefox
  Response.Cache.SetExpires(DateTime.Now.AddDays(-1));
  Response.Cache.SetCacheability(HttpCacheability.NoCache);
  Response.Cache.SetNoStore();
  // Disallowed user to browse the page when not login
  if ( Session["adminuser"] == null )
  {
   Response.Redirect("index.aspx");
  }
  admin.Text = Session["adminuser"].ToString();
  Message.Text = "";
  delete.Attributes.Add("OnClick", "return confirm('Are you sure to delete the item?');");
  try
  {
   con = new SqlConnection(db);
   
   getID();
   if ( !IsPostBack )
   {
    BindGrid();
   }
  }
  catch ( Exception ex )
  {
   Message.Text = "<b>ERROR: " + ex.Message;
   Message.Style["color"] = "red";
   Message.Visible = true;
  }
 }
 // Datagrid Binding
 private void BindGrid()
 {      
  SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM ShippingRates ORDER BY ShippingRateID DESC", con);
  DataSet ds = new DataSet();
  sda.Fill(ds, "ShippingRates");
  Shippingdg.DataSource=ds.Tables["ShippingRates"].DefaultView;
  Shippingdg.DataBind();
 }
 // Paging on datagrid
 public void Paging(object sender, DataGridPageChangedEventArgs e)
 {
  Shippingdg.CurrentPageIndex = e.NewPageIndex;
  Shippingdg.DataBind();
  BindGrid();
 }
 // Get next Shipping ID 
 private void getID()
 {
  SqlCommand maxId = new SqlCommand("SELECT MAX(ShippingRateID) FROM ShippingRates", con);
  con.Open();
  
  string result = maxId.ExecuteScalar().ToString(); 
  int id = Convert.ToInt32(maxId.ExecuteScalar().ToString());
  int getId = 1;
  
  if (  !result.Equals("") || !result.Equals("Null") )
  {
   getId = id + 1;
  }
  con.Close();
       
  sidtxt.Text = getId.ToString();
 }  
 // Add data to database
 public void Add_Click(object sender,  EventArgs e)
 { 
  int sid = Convert.ToInt32(sidtxt.Text);
  double rates = Convert.ToDouble(ratetxt.Text);
  string country = countrytxt.Text; 
 
  try
  {
   string exist = "SELECT COUNT(*) FROM ShippingRates WHERE DeliveryCountry = '"+country+"'";
   SqlCommand query = new SqlCommand(exist, con);
   con.Open();
  
   int yes = Convert.ToInt32(query.ExecuteScalar().ToString());
   if ( yes > 0 )
   {
    Message.Text = "<b>Error: " + country + " already exist in the database<br>";
    Message.Style["color"] = "red";
    Message.Visible = true;
   }
   else
   { 
    string insertQuery = "INSERT INTO ShippingRates VALUES ("+sid+", "+rates+", '"+country+"')";
    SqlCommand SqlCom = new SqlCommand(insertQuery, con);
    SqlCom.ExecuteNonQuery();
    Message.Text = "<b>Record has been Added<br>";
    Message.Style["color"] = "red";
    Message.Visible = true;
   }
  }
  catch ( SqlException )
  {
   Message.Text = "<b>ERROR: Problem with query";
   Message.Style["color"] = "red";
   Message.Visible = true;
  }
  con.Close();
  getID();
  ratetxt.Text = "";
  countrytxt.Text = "";
  BindGrid();
 }
 // Delete checked items
 private void Delete_Click(object sender, System.EventArgs e)
 {
  DataGridItem dgItem;
  CheckBox chkItem = new CheckBox();
  Shippingdg.CurrentPageIndex = 0;
   
  for ( int i = 0; i < Shippingdg.Items.Count; i++ )
  {
   dgItem = Shippingdg.Items[i];
   chkItem = (CheckBox)dgItem.FindControl("delcb");
     
   if ( chkItem.Checked == true )
   {
    int key = Convert.ToInt32(Shippingdg.DataKeys[dgItem.ItemIndex]);
    string deleteQuery = "DELETE FROM ShippingRates WHERE ShippingRateID = "+key+"";
    SqlCommand SqlCom = new SqlCommand(deleteQuery, con);
    SqlCom.Parameters.Add(new SqlParameter("@sid", SqlDbType.Int, 20));
    SqlCom.Parameters["@sid"].Value = Shippingdg.DataKeys[dgItem.ItemIndex];
    SqlCom.Connection.Open();
    try
    {
     SqlCom.ExecuteNonQuery();
     Message.Text = "<b>Record has been deleted</b><br>";
     Message.Style["color"] = "red";
     Message.Visible = true;
    }
    catch (SqlException)
    {
     Message.Text = "<b>ERROR: Could not delete record</b>";
     Message.Style["color"] = "red";
     Message.Visible = true;
    }
    SqlCom.Connection.Close();
   }
  }
  getID();
  BindGrid();
 }
 // Reset the form
 private void Reset_Click(object sender, System.EventArgs e)
 {
  countrytxt.Text = "";
  ratetxt.Text = "";
 }
 // Back to shipping rates main page
 private void Cancel_Click(object sender, System.EventArgs e)
 {
  Response.Redirect("ManageShippingRates.aspx");
 }
}

First of all, considering that this is not a C# forum, the ones who try to solve your query might not necessarily have .NET to try out your code. Secondly, you need to give exact error messages which appear in the Firefox error console and paste the relevant code removing the C# mess if you plan on getting help from this 'Javascript' forum. Either that or repost in the C# forums.

I am very sorry if I cause any confusion. There is no error return when running the system using firefox browser. The only problem is validation using javascript is not working in firefox in which means that user can submit the form by entering any values and the values submitted are stored in the database.

If anyone ever encounter this kind of problem when developing web based system using javascript for client side validation using any language, please advice if you know why.

I have heard that coding for browser detection need to be added to solve the problem. Please correct me if I am wrong.

Thank you very much :)

The best way to get help would be to remove the C# code from the code above and post just HTML and Javascript so that testing it would be easy.

Did you also take into account what would happen if JavaScript is turned off in the browser security section?

Hi all,
I have similar problem. App works fine on IE, but FireFox doesn't fire javascript function. When I put checkbox on checked, row should change the color. This is my javascript code:

<head runat="server">
    <title>Unos dužnika</title>
    <LINK href="StyleSheet.css" type="text/css" rel="stylesheet">
    <script type="text/javascript">
    //declare global variables
    function chkSelect_OnClick(tableRowId, 
                   checkBox, rowIndex)
{
    var bgColor;
    bgColor = "#ebeaef";
    if(checkBox.checked == true)
        tableRowId.style.backgroundColor = "#ffffff";
    else
        tableRowId.style.backgroundColor = bgColor;

}
    </script>
</head>

Could you tell me what is the problem?

use the inbuild error console in firefox to know your error..its cool..
tool -> error console

first clear the console and then execute ur web app in firefox and continiously check for any error message in the error console

Hi all,
I have similar problem. App works fine on IE, but FireFox doesn't fire javascript function. When I put checkbox on checked, row should change the color. This is my javascript code:

...
<head runat="server">
    <title>Unos dužnika</title>
    <LINK href="StyleSheet.css" type="text/css" rel="stylesheet">
    <script type="text/javascript">
    //declare global variables
 	function chkSelect_OnClick(tableRowId, 
                   checkBox, rowIndex)
{
    var bgColor;
    bgColor = "#ebeaef";
    if(checkBox.checked == true)
        tableRowId.style.backgroundColor = "#ffffff";
    else
        tableRowId.style.backgroundColor = bgColor;
  
}
    </script>
</head>
...

Could you tell me what is the problem?

- I don't see you CALLING your code. You are loading the code, but not executing it. Maybe your strange syntax is an IE proprietary extension.

- You spelled onclick wrong (it's case sensitive), and placed it in the wrong place. onclick goes in the html tag you want to click on, not in the JavaScript code.

For instance, to call your function chkSelect when the mouse clicks on a certain div or on a certain paragraph, do this:

<html .... >
<head>
....
<script type="type/javascript">
....
function chkSelect(){
....
}
....
</script>
....
</head>
<body>
  ....
  <div onclick="javascript:chkSelect()">
  ....
  </div>
  ....
  <p onclick="javascript:chkSelect()">
  ....
  </p>
  ....
</body>
</html>

Almost any tag can contain an onclick attribute.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.