Sign up for and run a JavaScript function within an ASP.NET Page_Load event

Is there a way to both register and run a JavaScript function in ASP.NET during a Page_Load event? I need the function to validate the content of a textbox, and if it is empty, disable a save button.

function Validate(source, arguments)
{
}

Answer №1

Try using ClientScriptManager.RegisterStartupScript

For a detailed example, check out this link

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
  public void Page_Load(Object sender, EventArgs e)
  {
    // Define the name and type of the client scripts on the page.
    String csname1 = "PopupScript";
    Type cstype = this.GetType();

    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = Page.ClientScript;

    // Check to see if the startup script is already registered.
    if (!cs.IsStartupScriptRegistered(cstype, csname1))
    {
        StringBuilder cstext1 = new StringBuilder();
        cstext1.Append("<script type=text/javascript> alert('Hello World!') </");
        cstext1.Append("script>");

        cs.RegisterStartupScript(cstype, csname1, cstext1.ToString());
    }
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>RegisterStartupScript</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>
</html>

I trust this information will be useful for you

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

Ways to patiently wait in a for loop until the ajax call is completed

I am a beginner in web development and currently working on a small website project that involves using ajax to display new comments. Below is the function I have created: function show_comments() { $('div#P_all_posts>div').each(function () { ...

Is there a way to link the req.session.user from express-session to a chai-http request?

When it comes to my API, it relies on the express-session module for authentication. Each request is verified based on whether the req.session.user object exists within the request. The implementation can be seen in the snippet below: app.use(function(req ...

Retrieve specialized information from a json file

I have a JSON variable called json which contains some data in JSON format. I am attempting to extract a specific portion of that data. One way to do this is by using the index as demonstrated below: var newdata = json[listid].Taxonomies[0]; However, my ...

Sending data from a bespoke server to components within NextJS

My custom server in NextJS is set up as outlined here for personalized routing. server.js: app.prepare() .then(() => { createServer((req, res) => { const parsedUrl = parse(req.url, true) const { pathname, query } = parsedUrl ...

Changing VueJS duplicate values with v-model (:value, @input)

I'm encountering an issue with v-model in my custom component. I prefer not to use State or Bus. Currently, the component successfully returns a single value in App.js, but it duplicates itself. I'm struggling to resolve this problem, so any help ...

Issue arises when running R script on a cluster, whereas the script functions properly on a laptop

I'm puzzled as to why this issue keeps arising, despite testing different versions of R to rule out any version-related errors. The problem lies within one of my functions. replacement<-function(x){ x=replace(x,which(x=='0/3'),0) x= ...

The issue with CSS and JavaScript is causing the appended elements to not display properly in PHP code

I am currently facing issues with retrieving the grandchildren from my database table named referrals. Surprisingly, my code successfully retrieves the username of my grandchildren, but it does not display below the line of my child and there are no errors ...

When the phone locks, Socket.io experiences a disconnection

setInterval(function(){ socket.emit("stayalive", { "room": room }); }, 5000); I have developed a simple browser application with an interval function that is currently running on my phone. I am using Chrome on my Nexus 4 for debugging purposes. However, ...

Tips for retrieving a variable from an XML file with saxonjs and nodejs

I came across an xml file with the following structure: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE agent SYSTEM "http://www.someUrl.com"> <myData> <service> <description>Description</description> < ...

Deployment of multiple versions in Azure Web Sites is a breeze

Our company works with multiple clients who use Azure web sites to host our web application. Currently, when we upgrade a client to a newer version of our software, we have to upgrade all clients to the latest version simultaneously. However, we are looki ...

Having trouble resolving "react-native-screens" from "node_modules eact-navigation-stacklibmoduleviewsStackViewStackViewCard.js"? Here's how to fix it

Here is the command I used for setting up react app routes: npm i react-native-router-flux --save After restarting npm with "npm start," I encountered this error message: Unable to resolve "react-native-screens" from "node_modules\react-navigation- ...

Personalized user static folder in Node express

Can we achieve this functionality using node and express middleware? app.use('/',express.static('public')) app.get('/public', function() { app.use('/',express.static('public')) }) app.get('/public2 ...

Conceal the button once the page has been converted to an HTML format

Located at the bottom of the HTML page is a button that triggers an onClick function. Since the page only contains internal CSS, when users save the page (by right-clicking and selecting Save As) as an HTML file, it is saved without any additional folders ...

The overflow-anchor property is not effective for scrolling horizontally

My goal is to create a never-ending horizontal scroll that allows users to scroll both left and right. When users scroll to the left, new content should be added to the beginning of the scrollable element (similar to scrolling through a schedule history). ...

OWIN Cookie authentication does not trigger the OnValidateIdentity method

I've implemented the OWIN cookie authentication middleware and configured a custom OnValidateIdentity method to be called on all authenticated requests. Here is my setup: app.UseCookieAuthentication(new CookieAuthenticationOptions { ...

How to add an item to an array in JavaScript without specifying a key

Is there a way to push an object into a JavaScript array without adding extra keys like 0, 1, 2, etc.? Currently, when I push my object into the array, it automatically adds these numeric keys. Below is the code snippet that I have tried: let newArr = []; ...

Disabling functionality is not working properly when multiple expressions are added

One specific scenario involves using a radio button for selecting options and requiring users to confirm their selection using the JavaScript confirm method before enabling the next button. Take a look at the following code: HTML <body ng-controller ...

The TouchableOpacity function is triggered every time I press on the Textinput

Every time I press on a text input field, the login function is called This is the touchable statement: <TouchableOpacity style={InputFieldStyle.submitButton} onPress={this.login(this.state.email, this.state.password)}> <Text ...

What is the best way to make an ajax commenting system function from a separate directory?

I am facing an issue with implementing an ajax commenting system on my website. When I place all the code from the /comment directory directly in the root, everything works fine and the commenting system functions as expected on new pages. However, when I ...

Troubleshooting: Problems with AngularJS $http.get functionality not functioning as expected

I have a user list that I need to display. Each user has unread messages and has not created a meal list yet. I want to make two http.get requests within the main http.get request to retrieve the necessary information, but I am facing an issue with asynchr ...