I attempted to invoke a JavaScript function upon clicking an ASP button via the code behind, but unfortunately, it did not function as intended

My .aspx page contains a JavaScript function

<script type="text/javascript">
function openCity(evt, cityName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(cityName).style.display = "block";
    evt.currentTarget.className += " active";
}</script>

Additionally, I have an ASP button

<asp:Button ID="Button2" runat="server" Text="submit" OnClick="Button2_Click" />

In the .aspx.cs page, I included this code

 protected void Button2_Click(object sender, EventArgs e)
{
    ScriptManager.RegisterStartupScript(this, this.GetType(), System.Guid.NewGuid().ToString(), "openCity(event, 'Tokyo');", true);
}

Unfortunately, this implementation did not work as expected!

Answer ā„–1

I have encountered the same issue multiple times and found two solutions that usually help me get JavaScript working after a button click:

  1. Ensure that the script block is placed after the control declaration in the ASPX page. For example:

<body>
<asp:Button ID="Button2" runat="server" Text="submit" OnClick="Button2_Click" />
:
:
:
<!--other HTML stuff-->
<script>
//Put your script here
</script>
</body>

  1. If the above solution does not work, try using the JavaScript timeout function. For instance:

    protected void Button2_Click(object sender, EventArgs e)
     {
         ScriptManager.RegisterStartupScript(this, 
         this.GetType(),System.Guid.NewGuid().ToString(), 
         "setTimeout('openCity(event,\'Tokyo\'), 200);", true);
     }

I hope this helps you resolve the issue for now.

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

implementing AJAX to retrieve data from an ashx file in ASP.NET

I am in the process of creating a website and I need to access an ashx file that will provide me with a list of all processes running on the server. ...

Tips for properly setting and accessing data objects in React when utilizing a Firebase database

Iā€™m encountering issues with storing and retrieving data using the useState hook in React after fetching it from a Firebase database. The issue appears to be related to not all users having all values in the playerData data packet ā€“ for example, if a p ...

Any ideas on how to resolve this ajaxToolkit issue?

Just for your reference, here's what I'm trying to achieve: https://i.stack.imgur.com/GYaNz.jpg Error 1: Unknown server tag 'ajaxToolkit:CalendarExtender'. <ajaxToolkit:CalendarExtender FirstDayOfWeek="Monday" PopupPosition="Botto ...

Creating a personalized ESLint rule specifically for Redux reducers

Currently working with Redux and Redux Toolkit alongside ESLint presents a challenge. Sometimes, when adding my extraReducers, I find that I do not need both the state and action properties provided by Redux. As a result, ESLint throws an error in these c ...

Unusual problem arises when working with exclusions and inclusions in tsconfig.json

I've encountered a peculiar issue. When I specify the following in my configuration: "exclude": [ "node_modules", "**/__tests__", "**/*.test.*", "**/server-handlers/**/*", "**/ ...

What could be causing compatibility issues with materials other than MeshNormalMaterial when using a mesh created with ThreeBSP.js?

When it comes to creating a dice, I've noticed that it only looks like a dice when using MeshNormalMaterial in the second last line (result = resultBSP.toMesh(materialNormal);). If any other material is used, it just ends up looking like a cube with n ...

Exploring Angularjs: Navigating to a particular element within ng-repeat

I created a custom directive that generates a list of buttons using ng-repeat: HTML <div ng-controller="toggleButtonController" ng-init="init()" id="parent"> <div ng-repeat="btn in setting" style="display:inline"> <button class ...

Mongoose Error: The function 'mongooseSchemahere' is not recognized as a valid function

Here is the mongoose Schema setup in models/user.js: const mongoose = require('mongoose'); const userSchema = mongoose.Schema({ loginId: String, firstname: String, lastname: String, eMail: String, password: String, acti ...

Problem with unique geometry and facial orientation

Just dipping my toes into ThreeJS and I'm encountering a small issue, likely due to incorrect usage. I'm attempting to create a custom geometry and manually define the faces normals. I've set one normal in one direction and another in the o ...

Playing sound on the client side using ASP.NET pragmatically

Is there a way to play music on an ASP.NET webpage when a specific condition is met, such as during a postback every 10 seconds? It should act like a notification sound. For example: If x > 2, playsound() End If I attempted the code below, but it ...

ESLint's no-unused-vars rule is triggered when Typescript object destructuring is employed

I'm encountering an issue with my Typescript code where I am destructuring an object to extract a partial object, but it's failing the linter check. Here is the problematic code snippet: async someFunction(username: string): Promise<UserDTO> ...

Exploring Netbeans 7.3 for Enhanced JavaScript Autocomplete with Parameters

Ever since the upgrade to netbeans 7.3, I've encountered an issue where netbeans no longer automatically provides me with parameter names. For instance, When I see "methodA(param1, param2) xxx.js" in the autocomplete pop-up, clicking on it or pressi ...

Rendering sibling components on Multiple Select Material UI in React

Here is my current challenge: I am trying to implement a multiple select feature with checkboxes in React using Material UI. The desired outcome should resemble the image linked below: https://i.stack.imgur.com/TJl8L.png I have structured my data in an a ...

Exporting a gridview to excel while excluding the footer section can be achieved by utilizing

Is there a way to export an asp.net gridview to excel without including the footer row? ...

Gulp and Babel: Module Not Found Error

I am facing an issue with my project setup using gulp and babel. Everything seems to be functioning correctly, except for when I create a module and import it after conversion from ES6 to ES5. At that point, it fails to work and displays the following erro ...

A straightforward method of transmitting data from JavaScript to the Python back-end within a Streamlit application

Utilizing the st.components.v1.iframe, I integrated an authentication system that sends a token back to the parent when a user is authenticated. The iframe content is as follows: <script src="remote/auth.js"></script> <scri ...

Create a custom loading spinner for a jQuery AJAX request

How can I add a loading indicator to my Bootstrap modal that is launched from a link? Currently, there is a 3-second delay while the AJAX query fetches data from the database. Does Twitter Bootstrap have built-in functionality for this? UPDATE: Modified J ...

Stopping the execution of jQuery().load()

The .load() feature in the jQuery library allows users to selectively load elements from another page, based on specific criteria. I am curious to know if it's feasible to stop or cancel the loading process once initiated. In our program, users can e ...

The hook call you made in next.js/react is invalid and cannot be

I recently followed a tutorial on creating a hamburger menu in react/next.js. You can check out the tutorial here. import { useState } from "react"; import user from '../styles/userview.module.css' export function PageHeader() { con ...

What is the most effective way for me to utilize callback functions and setTimeout in my code?

I am facing an issue where I need to transfer data from fileExistance to result and then export the result to budget.js in the router folder. However, I am encountering the following error: internal/validators.js:189 throw new ERR_INVALID_CALLBACK(callbac ...