Is there a way to execute a JavaScript function within a loop?

I need to repeatedly call a JavaScript function multiple times. I have attempted to do so in the following way:
In Script

 function changeIt(strgr , idx) {
    //SomeCode
    return;  
 }    

In C#

 protected void btn_Click(object sender, EventArgs e)  
 {  
      string strgr = 001;
      for(int i=0; i<3; i++)  
      {  
          base.RunScriptBottom("changeIt(" + strgr + "," + i + ");");  
      }
 }  

Unfortunately, the script function is only being called once. What should I do?
Best regards

Answer №1

For more information on ClientScriptManager.RegisterStartupScript, please visit this link

Additionally, you have the option to create a JavaScript function to iterate and call from the server side just once.

 function changeAll(strgr , from, to) {

   for(int i = from, i< to; i++)
      changeIt(strgr ,i);
 } 

Server Side:

protected void btn_Click(object sender, EventArgs e)  
 {  
      string strgr = 001;

          base.RunScriptBottom("changeAll(" + strgr + ",0,3);");  

 } 

Answer №2

To accomplish this task, it is recommended to incorporate a client event.

<asp:Button Text="click me" runat="server" OnClientClick="executeLoop()" />
<script type="text/javascript">
    function executeLoop() {
        var number = 001;
        for(var i=0; i<3; i++)  
        {  
            performAction(number + "," + i );  
        }
    }
</script>

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

jQuery fade in problem or alternate solutions

When I send a post request to a file and input the response into id='balance', I would like it to have a flickering effect or fadeIn animation to alert the user that it is being updated in real time. I attempted to use the fadeIn() method but it ...

No data found in Node.js after receiving AngularJS POST request

I've been working on sending a straightforward POST request to my server using AngularJS. The request successfully goes through and reaches the controller on the backend, but strangely, req.data is appearing as undefined. Front End Controller: funct ...

What is the best way to incorporate client and server components in nextJS when params and query parameters are required?

I'm having difficulty understanding the client/server component concept in nextJS 14 (using app router). Below is an example page illustrating how I typically structure it and what components are required: I need to extract the id value from params ...

Steps to creating a nested function

I'm still learning the ropes of Javascript, and I've been working on creating a personal library to streamline my coding process. Here's the code snippet I've come up with. function myLibrary() { let _this = this; this.addString = ...

Integrating the SecuSearch SDK PRO biometric device into an ASP.NET application requires following a set of

I am currently experiencing difficulties integrating the Secugen Hemister Pro Duo SC PIV Biometric device. Below are the steps I have taken: Installed the driver for the device Installed the fingerprint recorder application Ran the Finger Print Recorder ...

Combining the power of AngularJS with the versatility of sails

A project I'm working on involves utilizing sails.js for back-end and AngularJS for front-end. My plan is to use the Yeoman-angular generator https://github.com/yeoman/generator-angular to create the Angular app first. Once the front-end development i ...

Guide on creating a Discord bot that can delete its own message in a private message (DM) using Discord.js

Working on my Discord.js Discord bot, I'm exploring the option of having the bot delete its own message from a DM chat. Is it feasible to achieve this and if so, what code should I use? Attempting msg.delete() is throwing an error mentioning that this ...

I'm having trouble understanding why I can't access the properties of a class within a function that has been passed to an Angular

Currently, I have integrated HTML 5 geolocation into an Angular component: ... export class AngularComponent { ... constructor(private db: DatabaseService) {} // this function is linked to an HTML button logCoords(message, ...

Can we rely on the render method to display the updated state immediately after invoking setState within

Is it guaranteed that the state will exist in the render method if I call setState within componentWillMount without using a callback? According to Facebook, "componentWillMount is called before render(), therefore calling setState() synchronously in this ...

Postgres.js Date Range query failing to fetch any results

Recently, I have been utilizing the Postgres.js npm module to interact with a PostgreSQL database Below is the code snippet for executing the query: let startDate = '2020-01-28 08:39:00'; let endDate = '2020-01-28 08:39:59'; let table ...

Ways to eliminate a group of words from a string using JavaScript

I have developed a unique function that efficiently deletes specified words from a given string. Here is the function: var removeFromString = function(wordList, fullStr) { if (Array.isArray(wordList)) { wordList.forEach(word => { fullStr ...

Uncovering the jsPlumb link between a pair of identifiers

Could someone help me understand how to disconnect two HTML elements that are connected? I have the IDs of both elements, but I'm not sure how to locate their connection in the jsPlumb instance. Any tips on finding the connection between two IDs? ...

Avoid the need for users to manually input dates in the Custom Date Picker

After referencing this custom Date picker in ExtJs with only month and year field, I successfully implemented it. However, I am facing an issue where manual entry into the date field is not disabled. My goal is to restrict input for that field solely thr ...

Opting for classes over IDs

Within the parent class, there are two divs. One is located using $(this).parent('div').next('.deal-rolldown').show(); while the other $(this).parent('div').next('.client-rolldown').show(); does not seem to function ...

When an element in vue.js is selected using focus, it does not trigger re

One of my tasks involves tracking the last selected input in order to append a specific string or variable to it later on. created: function () { document.addEventListener('focusin', this.focusChanged); } focusChanged(event) { if (event ...

What encoding does XDocument.Load default to assuming?

If I were to employ the XDocument.Load method for parsing an XML file... var x = XDocument.Load("somefile.xml"); ...and if said file lacks a declaration like <?xml version="1.0" encoding="..."?> at the beginning... <MyRootElement> ... < ...

Utilize Express and Mongodb to interact with API and database queries

Looking for assistance with my project on creating a gaming server list. Users should be able to add their server by entering a title, IP, port, and some information about it. However, on the homepage, I also want to display the number of players and whet ...

The ng-model is not properly syncing values bidirectionally within a modal window

I am dealing with some html <body ng-controller="AppCtrl"> <ion-side-menus> <ion-side-menu-content> <ion-nav-bar class="nav-title-slide-ios7 bar-positive"> <ion-nav-back-button class="button-icon ion-arrow-le ...

The View Component is experiencing issues with loading the CSS and JS files correctly when an AJAX call is made

Hey there! I'm having trouble loading a view component via ajax when the button is clicked. It seems like the css and javascript are not working properly. Check out the ajax call for the controller to load the component: $.ajax({ url: window.locat ...

Discover the worth within the outcome obtained from the AJAX request

I have an action that returns a tuple containing a boolean value and a string. How can I retrieve the first boolean value from the result, which could be either true or false? This is the action: public Tuple<bool, string> Check This is the AJAX c ...