Using a JS file to trigger a JavaScript function in an ASP.NET application

My JavaScript is referenced in my page this way:

<script src="JScript1.js" type="text/javascript"></script>

The following are the functions 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 want to call these functions from my code behind and assign them to a custom validator.

I have attempted the following but it's not working:

<asp:CustomValidator ID="custValCountry" runat="server" ValidationGroup="Country"
                        ValidateEmptyText="true" ControlToValidate="TextBox1" ClientValidationFunction="javascript:f"
                        ErrorMessage="Other is required"></asp:CustomValidator>

In my RowDataBound event, I have written the following which is also not functioning as expected:

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 + "');");
        }
    }

Any help would be appreciated.

Answer №1

Typically, ASP.NET does not process static JavaScript files, meaning that attempting to reference an element by its ASP.NET ClientID will not function as expected:

var gridview = document.getElementById("<%=Gridview1.ClientID%>");

To work around this limitation, assign a fixed ID to the grid element and reference it directly:

var gridview = document.getElementById('my-grid');

<asp:GridView ID="my-grid" ClientIDMode="Static" runat="server" ...>

If necessary, consider alternative methods for identifying elements.

Furthermore, the following function may appear to be ineffective:

function multiplication(txtQuantity) {
var weight = document.getElementById(txtQuantity).value;
}

It seems that the retrieved weight value is not being utilized in any meaningful way.

Answer №2

It's important to remember that your JavaScript functions are executed in the user's browser, separate from the server where your back-end code operates. To utilize these functions in your code behind, you'll have to replicate them there as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can the value be extracted from a Dijit.Calendar?

This is a straightforward question, or at least I believe it is. In my code, I have declared a Dijit.Calendar and it loads successfully and functions well. However, I am confused about how to retrieve the selected value. My goal is to update a textbox ne ...

The simultaneous loading of ng-include and ng-view is not supported

I have a simple app structure consisting of headers, footers, and ng-view on the homepage. When I enter the page, I notice that the two ng-include files load first, followed by the ng-view which pushes the footer to the bottom. This causes a brief flashing ...

Having trouble getting the SelectedIndex_Changed event to work with your ASP.Net Drop Down?

Having issues with the DropDown Selected Index Changed event not firing as expected in the code below: <asp:DropDownList ID="DropCourseLevel" runat="server" CssClass="form-control m-input" AutoPostBack="true" OnSelectedIndexChanged="DropCourseLevel_Se ...

Toggle jQuery slide effect showing all elements and not hiding other list items

I'm utilizing this to display a sub list: function showSublist(element) { $(element).find('ul.joinus_subtext').slideToggle(); } and below is the HTML markup: <ul class="joinus"> <li onclick="showSublis ...

Is the hook useEffect behaving improperly due to dependency issues?

I'm facing an issue with an infinite loop occurring inside the useEffect hook. I want to trigger a new request only when the id dependency changes. However, when I don't pass data, I encounter problems with updating the state using setData. On th ...

What is the best way to highlight specific text in React components that is passed from an object?

This is the page HTML content where an object is created. A portion of the description needs to be emphasized: const agencyProps = { title: "Managed agency selection", paragraph: "Strengten your onboarding process", videoImage: { ...

What is the best way to transfer data to the database without refreshing the page?

I've been attempting to send data to a database using AJAX/PHP, but I'm encountering errors. Despite reviewing codes from various sources, none seem to be functional and I keep receiving the error message: TypeError: 'stepUp' called on ...

Looking for help positioning arrows in HTML/JS for a pop-up gallery

Currently, I am working on developing a Flask application that displays a list of videos fetched from a database in an HTML template. Upon clicking a video link, the video opens and plays in a pop-up window with arrow buttons for navigating to the next or ...

Images that are loaded from a file and appended cannot be chosen or selected

I have implemented a script that is designed to load images from a specific folder and then append them to a designated div: $(function() { var folder = "img/moreprojects/"; $.ajax({ url : folder, success: function (data) { ...

Switching the color scheme between mobile and desktop devices to make the background look

As a newcomer to threejs, I have just begun learning and developing with this technology. I am aware that certain features may be different on mobile browsers compared to desktop ones due to limitations. However, I have encountered an issue that I cannot s ...

Transform an SQL query into an Entity Framework LINQ query

Here is the query that I am currently working with: select distinct (case when object like'%service%' then (object) when host like '%service%' then (host) when class like '%service%' then (class) when p ...

Is the npm mqtt module continuously running but not performing any tasks?

I'm relatively new to the world of JS, node.js, and npm. I am attempting to incorporate a mqtt broker into a project for one of my classes. To gain a better understanding of how it functions, I installed the mqtt module from npm. However, when I tried ...

What is the best way to implement lazy loading for headless UI Dialog components in a React

Is there a way to implement lazy loading for the headless ui Dialog component while preserving transitions? Below is the current implementation that almost works: // Modal.js const Modal = ({ isOpen }) => { return ( <Transition show={isOpen ...

Could altering the visibility of a virtual method from protected internal to just protected be considered a disruptive modification?

Would switching a method's visibility from protected internal to protected qualify as a disruptive change for external callers and implementers of the class? Keep in mind that this method is virtual, allowing it to be overridden in subclasses. Origi ...

event is triggered without requiring an onClick function to be present

I'm currently working with an API to populate a list using the fetch function and promises. Each item in the list has a delete button that should remove it when clicked. However, I'm facing an issue where the deletion function is triggered automa ...

Exploring the combination of Babel and Next.js: Integrating custom scripts into a project

Hello, I am currently learning next.js and facing a common issue that I need help with. I have created my own ES6 JavaScript library and now I want to convert it to babel so I can use it in my next.js application. Is there a way to configure babel for sp ...

What happens to the code within a TransactionScope block that is not executed until the scope is either committed or rolled back?

After reading up on the TransactionScope and this article, I'm still puzzled about 2 things: Is it true that when SqlCommand.ExecuteNonQuery is executed, it doesn't actually run until scope.Complete() is called? If so, where do all the executed ...

Guide to animating an svg icon when hovering and when it comes into view on the screen

Seeking a way to animate the SVG icon upon mouse hover or when it comes into view. Encountering an issue where the icon animates on appearance but not on mouse hover. Any straightforward solutions for this? Below is the code snippet. Using window.addEve ...

Pass props in Reactjs depending on the component that has been loaded

I am seeking guidance on how to successfully pass a ReactJS prop from a component to my app during its loading process. I have managed to pass the value when my props are in app.js, but I am unsure of how to handle the prop when it is loaded from a separat ...

Transferring WIF to a distinct domain using AJAX

We are managing two distinct domains, one is hosting a secured API and the other serves as the frontend website. Our goal is to establish an ajax request from the website to the API while utilizing the credentials of the currently logged-in user. To achie ...