What is the best way to include Javascript in a dynamically populated checkbox list?

I have successfully implemented a checkboxList control that I manually populated with data and integrated with JavaScript:

<script type="text/javascript">
    function ShowHide(chk, txt,txt2) {
        //Get the Textbox based on selected checkbox
        ctrltxt = document.getElementById(txt);
        ctrltxt2= document.getElementById(txt2);
        //Check if checkbox is checked or not
        if (chk.checked) {
           //Show the Textbox
           ctrltxt.style.display = 'block';
           ctrltxt2.style.display = 'block';
         } else {
           //Hide the textbox
           ctrltxt.style.display = 'none';
           ctrltxt2.style.display = 'none';
         }
     }
     </script>

        <table style="border: 0; border-style: solid">
            <tr valign="top" style="background-color: #f5f7f7; font-size: large; white-space: nowrap;">
                <td style="font-size: large; font-weight: bold;">Request a Review of:</td>
                <td>
                 <asp:CheckBoxList ID="ckRequestReview" runat="server" CssClass="cb" Style="border-width: 0;" RepeatDirection="horizontal" RepeatColumns="4" RepeatLayout="Table">
                <asp:ListItem onclick="ShowHide(this,'txtTitleChange','classtitles');">Job Title</asp:ListItem>
                <asp:ListItem onclick="ShowHide(this,'txtPayGradeChange','gradeclass');">Pay Grade</asp:ListItem>
                <asp:ListItem onclick="ShowHide(this,'txtClassSpecChange','clssSpec');">Specs</asp:ListItem>
                </asp:CheckBoxList>
                </td>
            </tr>
        </table>

The code snippet above pertains to this specific question.

Initially, when a user selects an item like Job Title from the ckRequestReview checkboxlist control, the textboxes txtTitleChange and classtitles become visible for entering data.

This implementation has been working well so far.

However, based on user feedback requesting to retain selected items in the checkbox list, I decided to dynamically populate the checkboxList from a database. Here's how it's done now:

    Private Sub PopulateChoices()

    Using conn As New SqlConnection()

        conn.ConnectionString = ConfigurationManager.ConnectionStrings("CNchoices").ConnectionString()

        Using cmd As New SqlCommand()

            cmd.CommandText = "select * from muytable"
            cmd.Connection = conn

            conn.Open()

            Using sdr As SqlDataReader = cmd.ExecuteReader()

                While sdr.Read()

                    Dim item As New ListItem()

                    item.Text = sdr("ckRequestReview").ToString()

                    item.Value = sdr("ID").ToString()

                    item.Selected = Convert.ToBoolean(sdr("IsSelected"))

                    ckRequestReview.Items.Add(item)

                End While

            End Using

            conn.Close()

        End Using

    End Using

End Sub

Question:

Now, I need to know how to integrate the previously mentioned JavaScript functionality with this dynamically populated version of the checkboxList. The goal is for any selected item to remain selected even after form submission.

Is there a way to achieve this without querying the database on another page, as users prefer all actions to be completed on a single page?

Answer №1

If you want to enhance client-side attributes for a ListItem, consider using the Attributes collection.

Take a look at this example code snippet that demonstrates how to achieve this:

   While sdr.Read()

       Dim item As New ListItem()

       '-- Feel free to customize the JavaScript code below
       item.Attributes.Add("onclick", "ShowHide(this,'txtTitleChange','classtitles');") 

       item.Text = sdr("ckRequestReview").ToString()

       item.Value = sdr("ID").ToString()

       item.Selected = Convert.ToBoolean(sdr("IsSelected"))

       ckRequestReview.Items.Add(item)

   End While

(Note: This handwritten code is shared solely for instructional purposes and may contain errors)

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

What is the best way to implement my Vanilla JS Array manipulation technique in a ReactJS environment?

https://i.sstatic.net/ZRGsS.jpgMy REST API development is in its final stages, and I'm currently facing a challenge with converting an array received from the backend into either a Nested Object of Objects or an array of objects. This conversion would ...

JavaScript - Unable to access the toLowerCase method of an undefined value

Struggling to identify the issue, yet encountering the same persistent error! The problem persists even when alternative methods such as includes are attempted. let notes = [{},{ title: 'My upcoming journey', body: 'I am planning ...

Path taken to reach the view requested by Node.js server

Snippet of Controller Code: bina: function(req, res) { var request = require('request'); request({ url: 'http://localhost:3000/bina/', method: 'GET', }, function(err, res, body) { ...

Add an array to an existing array of objects

I am working with an array of objects displayed below. var myArray = [ { Data: '455', Note: 'tre', Id: '4' }, { Data: '456', Note: 'bre', Id: '5' }, { Data: '457', Note: 'cre&ap ...

When attempting to reference from a variable, you may encounter an error stating that setAttribute

In my VueJS project, I am facing an issue with dynamically adding the width attribute to an inline SVG code stored in a variable called icon. Despite having the correct SVG icon code in the variable, the setAttribute method is not working as expected and t ...

Three.js Image Processing with Effect Composer

After reviewing the example located at: I am intrigued by the possibility of applying post-processing effects on a duplicate of the initial data set. Essentially, I am interested in showcasing the original rendering of my scene in one container while simu ...

Display a Div when an image is clicked using JavaScript

I am attempting to create a clickable image that reveals a div when clicked. The catch is that the div can only be shown by clicking the image, not hidden again. Clicking on another image will replace the existing div with a new one. I was able to achieve ...

An unexpected error occurred: Angular is still not functioning correctly even though ng-route has been

Help! I'm encountering this dreaded error message: angular.js:68 Uncaught Error: [$injector:modulerr] Failed to instantiate module usersApp due to: Error: [$injector:modulerr] Failed to instantiate module ngRoute due to: Error: [$injector:nomod] Modu ...

When attempting to showcase array information in React, there seems to be an issue with the output

After printing console.log(response.data), the following output is displayed in the console. https://i.sstatic.net/LLmDG.png A hook was created as follows: const [result,setResult] = useState([]); The API output was then assigned to the hook with: setRe ...

The Javascript Navbar is malfunctioning on Firefox

Currently, I am working on a horizontal menu that includes submenus. My goal is to use Javascript to display the submenu when a user hovers over the parent menu. I created a JSFiddle example, which seems to be experiencing issues in FireFox! However, it w ...

Transform jQuery UI Slider input into clickable links

Is there a way to turn the jQuery slider values into clickable links? For example, if the slider is at 1920, can it redirect the user to another page? I've included the code in a fiddle: http://jsfiddle.net/up6Bx/ Any assistance would be greatly app ...

What is the proper way to connect with the latest Set and Map objects?

Can Angular 1.* ng-repeat function with Set and Map new objects? Is there a roadmap to implement this integration? ...

Identify the specific element that activated the MutationObserver across multiple elements

After exploring a helpful Stack Overflow post, I discovered that it is feasible to monitor multiple elements using a single MutationObserver object. In order to track the text of two specific elements on a website, I crafted the following script: var secon ...

What is the best way to attach an attribute to a element created dynamically in Angular2+?

After reviewing resources like this and this, I've run into issues trying to set attributes on dynamically generated elements within a custom component (<c-tabs>). Relevant Elements https://i.stack.imgur.com/9HoC2.png HTML <c-tabs #mainCom ...

Deactivate "When the viewModel attribute holds the phrase 'some text'"

I came across this answer on Stack Overflow regarding checking for a value in Knockout, but it seems to be outdated. I am attempting to achieve something like this: <li> <span data-bind="text: Subject"></span> <!-- ko if: Subjec ...

Inquiry into the use of Jquery.ajax()

Hey there, I'm curious about using Jquery Ajax to retrieve a numeric value from a website. Any suggestions on where I should begin? Any advice would be greatly appreciated. Thanks in advance! Best regards, SWIFT ...

Limiting the invocation of the listener method in f:ajax depending on the return value of onevent

I am looking to check if the Onevent javascript function returns true or false. My goal is to restrict the listener method call based on the return value of the Javascript function. However, the code snippet provided is causing a syntax error in Firebug. ...

Seeking advice on Javascript prototypes - how can I execute a function within a prototype without using "this"?

let Human = function (userName, userAge) { this.userName = userName; this.userAge = userAge; }; Human.prototype.sampleProto = function () { console.log(this.userName + " == " + this.userAge); ...

Laravel Mix causes errors when running `npm run dev` and breaks the package

My nodejs package is built using ES6 features such as 'let', the spread operator (...) and default values for function arguments. However, when I run npm run production with Laravel Mix, an error message appears: ERROR Failed to compile with ...

React - utilize a variable as the value for an HTML element and update it whenever the variable undergoes a change

I'm on a mission to accomplish the following tasks: 1.) Initialize a variable called X with some text content. 2.) Render an HTML paragraph element that displays the text from variable X. 3.) Include an HTML Input field for users to modify the content ...