What is the procedure for populating a listbox with items selected from an array?

On my aspx page, there is a listbox (techGroups) with preselected items that users can change. I also have a reset button that should restore the listbox to its original selections when clicked. However, I am encountering an issue where only the first preselected item remains selected after clicking the reset button.

I created the following JavaScript function for the onclientclick event of the reset button. It retrieves the preselected items from a hidden field and attempts to reselect them in the listbox:

function reset() {
       var selectedGroups = hiddenfield1.value.split(","); // The preselected items are saved in a hidden field.
        for (var i = 0; i < techGroups.options.length; i++) {
            for (var j = 0; j < selectedGroups.length; j++) {
                if (techGroups.options[i].value == selectedGroups[j]) {
                    techGroups.options[i].selected = true;
                }
            }
        }
}

If anyone could review my code and point out what might be incorrect, I would greatly appreciate it. Thank you.

Answer №1

Is jQuery permitted to be used? If yes, you can view it in action by clicking on the link below (if not allowed, please disregard):

http://jsfiddle.net/sW8HX/4/

Answer №2

There could be a potential reference issue related to the DOM. To address this, you can try the following solution:

JavaScript:

<script type="text/javascript">
window.onload = function () {
    var btnReset = document.getElementById("btnReset");
    btnReset.onclick = function () {
        var hid1 = document.getElementById("hiddenField1");
        var techGroups = document.getElementById("techGroups");

        var selectedGroups = hid1.value.split(","); // Saved preselected items in a hiddenfield

        for (var i = 0; i < techGroups.options.length; i++) {
            for (var j = 0; j < selectedGroups.length; j++) {
                if (techGroups.options[i].value == selectedGroups[j]) {
                    techGroups.options[i].selected = true;
                }
            }
        }
    };
};
</script>

Markup:

<form id="form1" runat="server">
<div>
    <input type="hidden" id="hiddenField1" value="aa,bb,cc" />
    <select id="techGroups" size="4" multiple="multiple">
        <option value="rr">rr</option>
        <option value="aa">aa</option>
        <option value="cc">cc</option>
        <option value="zz">zz</option>
        <option value="bb">bb</option>
        <option value="dd">dd</option>
    </select>
    <input type="button" id="btnReset" value="Reset" />
</div>
</form>

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

I have encountered a node.js error related to the 'Require Stack'

Encountering an error in my node.js application when trying to open a .js file { code: 'MODULE_NOT_FOUND', requireStack: } Unable to determine the root cause of this issue I have tried re-installing Node.js and its packages, removed and added b ...

Exploring the world of variable scopes in Node.js

I'm new to exploring the world of node.js, particularly trying to grasp the concept of asynchronous processing loops. Let's say I have an array called var counter = []; declared at the beginning of my server.js script. Next, I have a POST handl ...

Multiple users accessing ASP.net

A clock in/out site presents a problem when multiple users log in. User A sees his check in/outs, but once user B logs in, when A refreshes the page, he now sees B's data. It seems like the issue lies in storing the username as a public variable whe ...

Encountering issues when trying to combine Sequelize with TypeScript

As I attempted to transition my NodeJs application to TypeScript, I encountered issues with Sequelize. Upon attempting to implement the code from a website, an error occurred: This expression is not constructable. Type 'typeof import("/home/de ...

Imitate a hover effect

In my list, I have images and descriptions set up in the following format: <li> <img class="photography" src="PHOTO/boat.jpg" alt="Boat on sea." /> </li> <li><div id="description" class="description"> <p>BOAT</p> ...

What is the process for configuring the home page in the Godaddy file manager?

After successfully hosting my website on GoDaddy, I encountered an issue where typing my domain name in the address bar led to a "Maintenance" window. However, when I added "/Home.aspx" to the end of the URL, it redirected me to the correct home page. I ...

Exploring the World of Vue.js Object Imports

I am currently encountering an issue involving the importing of Objects from App.vue into a component. To provide context, this project consists of a Navigation Drawer component and an App.vue file. The Navigation Drawer contains Vue props that can be dyna ...

Emphasize the currently selected element in jQuery and convert its attributes into a

In an effort to enhance accessibility debugging, I've been working on a script that can identify which element has focus and display it in the console. However, I'm only interested in seeing what is printed in the HTML, not every single detail. S ...

Vue components: Using `object[key]` as a prop does not trigger reactivity

I'm attempting to bind a value from an Object into the prop of a Component, but unfortunately it is not reacting as expected. Despite using $this.set, the reactivity issue persists. Below is my template: <div class="grid"> <emoji-card v-fo ...

How to display information from a JSON file using dynamic routing in a React.js application

I'm currently working on a project to replicate Netflix using reactjs, but I've hit a roadblock and can't figure out what to do next. I've tried watching YouTube tutorials and reading articles online, but I haven't been able to fin ...

Is it possible to use function declaration and function expression interchangeably?

As I dive into learning about functions in Javascript, one thing that's causing confusion for me is the difference between function declaration and function expression. For example, if we take a look at this code snippet: function callFunction(fn) { ...

The provided argument in Typescript does not match the required parameter type, which should be a string

Encountering a TypeScript error with the following code: if (this.$route?.query?.domainName) { this.setDomain(this.$route.query.domainName); } The code snippet above is causing the following error message: TypeScript - Argument of type 'string | ...

Searching for single and double quotes within a string using RegExp in JavaScript

I have encountered an issue while searching for a substring within a string using the code below: mystring.search(new RegExp(substring, 'i')) The reason I am utilizing new RegExp is to perform a case-insensitive search. However, when the string ...

What is the best way to calculate the number of days between today's date and the end of the current month using Moment.js?

Here's the current code snippet I am working with: const moment = require('moment') const m = moment const currDay = m().format('D') const dayOfWeek = m().format('dddd') const daysInMonth = m().daysInM ...

What is the method to retrieve a value from a function call when a button is pressed?

Exploring the world of JavaScript, I'm currently working on a small program in React Native. My goal is to create a function SampleFunction2 that returns census data, and then render it on a FlatList when a button is pressed. Am I missing something by ...

Reload the MEN stack webpage without the need to reload the entire page

I am in the process of developing a data analytics dashboard using the MEN stack (MongoDB, Express.js, Node.js). I have successfully implemented functionality to display real-time data that refreshes every 5 seconds without the need to reload the entire ...

Why does the DropDownList automatically choose the first item when there are repeated data value fields?

Persistent Issue: I am encountering a problem with my DropDownList where the selected input text is not retained based on the DataTextField="COLUMNS_NAME" and DataValueField="DATA_TYPE" properties. Instead, it always defaults to the first value in the list ...

Changing the value of a property in an object based on the object's attribute in JavaScript

I have a JSON data set like this: inputData = [ { id : 179849, name : alex , lastname: sanchez}, { id : 788539, name : Paul, lastname: bearer}, { id : 282169, name : Jean, lastname: nobel}, ... { id : 632785, name : Maria, lastname: parak} ] I am looking ...

Issue with Accordion Panel Content Scroll Bar

Hello there, I've encountered a puzzling problem with my website. My objective is to insert a Time.ly Calendar widget into one panel of my accordion. On this page, "TOURNAMENTS: , the widget appears exactly as desired. However, when I replicate the c ...

Tips on including various font awesome icons in Vue.js

I am working on designing a section for an app that will feature three tabs, each with its own unique Font Awesome icon. Currently, I have set up the tab structure as shown below, but only one icon is displaying in the tab: <div class="tab"> ...