Ways to trigger a JavaScript function upon the first page load

I have a query regarding the implementation of a script that loads country options from a predefined list. I am facing an issue where the list reloads every time the page is loaded, and when I click on a button to save the information, it resets back to the beginning of the list. Can you suggest the most suitable window method to overcome this challenge? I explored several alternative window methods but none provided a viable solution. The onloadstart method also did not yield the desired outcome.

Furthermore, my script is embedded in the User Control page, therefore I would prefer not to invoke the function from the codebehind.

window.onload = function () {

       var countryElement = document.getElementById('countryId');

       var listOfCountries = ["Select Country","Afghanistan", "Albania", "Algeria" ...; // (Truncated for brevity)

       countryElement.options.length = 0;
       for (var i = 0; i < listOfCountries.length; i++) {
           countryElement.options[i] = new Option(listOfCountries[i]);
       }
   }

Answer №1

The issue lies in the combination of server-side and client-side code within your project. By clicking the button, a postback is triggered to the server, resulting in the page being sent back to the client with the onload script running again and retaining previous values.

To resolve this, utilize the IsPostBack property to identify when the page is initially loaded and include the client-side script only during that first load.

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

Having issues with accessing data from Informix database in PHP due to an undefined index?

I am encountering the following error multiple times per row: Notice: Undefined index: enviopre in /opt/lampp/htdocs/pruebax/pruebaxone.php on line 34 Notice: Undefined index: enviofra in /opt/lampp/htdocs/pruebax/pruebaxone.php on line 35 Notice: Undef ...

How come the 'npm install canvas' command did not generate a JavaScript file as expected?

My venture into the world of node packages has just begun. I recently tried installing canvas to my project using this command: npm install canvas Prior to successfully executing the installation, it was necessary for me to first install gtk and cairo by ...

Multiple requests are being sent via AJAX

Despite numerous other posts addressing the same issue, I have not been able to find a solution for my problem. The AJAX request appears to be sent multiple times. var checkAllStatus = function () { $.ajax({ cache: false, type: "POST", ...

What is the best way to consolidate PHP code within a single echo statement?

Can someone assist me with wrapping all my HTML code in an echo("") for the AJAX responses? Your help is greatly appreciated. Please, I need assistance. Below is my code: <?php if (isset($_POST['getcart'])){ $cart_item_query="SELEC ...

Can an entire object be bound to a model in an Angular controller function?

In TypeScript, I have defined the following Interface: interface Person { Id: number; FirstName: string; LastName: string; Age: number; } Within a .html partial file, there is an Angular directive ng-submit="submit()" on a form element. A ...

Gulp Watch fails to identify changes in the SASS SCSS directory

After setting up Gulp to compile SCSS into CSS using NanoCSS and gulp-css for the first time, I encountered an issue. While my do-sass command successfully compiles SCSS and minifies CSS files, it does not run when placed within a watch task. Any changes ...

Encountering an issue of receiving undefined while attempting to retrieve the attribute of a

At first, there was just a single upload button for a photo The setup looked like this, with the script tailored specifically for that ID <div class="field"> <label>Photos</label> <div class="field_info" da ...

Ensure that the Jquery inview element functions both upon initial load and as the user scrolls

I've been working on implementing the inview function by adding and removing a class to an element, but for some reason it's not functioning as expected. Can anyone offer some assistance with this? http://jsfiddle.net/zefjh/ $.fn.isOnScreen = f ...

This browser does not support automatic publicPath in Webpack5

While I was working on webpack 4.44.2, I encountered this error when transitioning to webpack 5.0.0 ERROR in ./src/assets/sass/styles.scss Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js): Error: Automatic publicPath is not ...

How can I access URL parameters sent with XmlHttpRequest in GET method in an aspx page?

I need to extract the two parameters that have been passed in the URL. // Using an XMLHttpRequest to read a text file var xhr; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); alert("Object created"); } al ...

Need help with Jquery JSON Request - I can successfully retrieve the Array but struggling to showcase it

Seeking assistance with using an API that retrieves information about ARK servers, such as the number of online players. The API can be found at this link: ... I have managed to obtain the array using a basic script I stumbled upon, but I am not well-ver ...

Unable to assign user to Roles in the Web API

I’m currently working on a project that involves assigning specific roles to users in order to control access to API functions. When attempting to assign a user to a particular role, I encountered an exception that I find puzzling since the referenced de ...

Detecting a click on the background div in Angular without capturing clicks on child divs

Over at ollynural.github.io, I've been working on creating a pop-up div in the portfolio page that provides additional information about the project you select. To close the pop-up, I have implemented an ng-click feature so that clicking on the main p ...

Grunt integration for version control

After sticking to simple Html and Css for the longest time, I'm finally diving into JavaScript for a new project where I want to automate versioning. I've been following the SemVer Guidelines and my projects are currently versioned as "version": ...

Crafting a Visual Storybook with Express.js

I am currently working on developing a photo album app using MEVN. In this project, the value of req.body.ALBUM is used as the folder name and req.body.DESCRIPTION is designated for describing the content. The issue I have encountered so far is that whil ...

Check off all checkboxes and send their values to an AJAX script using a table

I currently have a table set up with checkboxes in the first column. By checking these boxes, an AJAX script is triggered that updates a PHP session variable with the selected values. This functionality is working smoothly. However, I am now looking to enh ...

Try employing an alternative angular controller when working with the bootstrap modal

I am trying to implement a bootstrap modal in my main HTML file, and I need some help on how to call another Angular controller for the modal. The button that triggers the modal is within a div that already has an Angular controller, and this is causing th ...

An effective method for appending data to a multidimensional array in Google script

Is there a way to expand a multidimensional array of unknown size without relying on a Google Sheets spreadsheet to manage the data? I've searched everywhere but can't find an example for a 3-dimensional array. Here's the challenge I'm ...

What is the best way to interrupt an animation and restart it?

On my webpage, I have implemented some anchors and links that navigate to these anchors. When I click on a link, the background-color of the anchor changes. I use animation to gradually fade out this color over 10 seconds - starting with white and then rem ...

Clicking on text triggers image display

My journey in coding is just starting and I have a good understanding of the basics of HTML, CSS, Javascript, and jQuery. I am trying to make an image appear when I click on text but struggling with the implementation. I'm working on a restaurant web ...