Having trouble retrieving selected values from a CheckboxList in JavaScript

In my asp.net application, I have a checkbox list that is defined as follows:

<asp:CheckBoxList ID="chbUserType" RepeatDirection="Horizontal" runat="server">
                    </asp:CheckBoxList>

I have populated this checkbox list using the following code:

chbUserType.DataSource = dtRoles;
        chbUserType.DataValueField = "idRole";
        chbUserType.DataTextField = "Title";
        chbUserType.DataBind();

        foreach (ListItem li in chbUserType.Items)
        {
            li.Attributes.Add("JSvalue", li.Value);
        }   

Now, I need to access the selected values of this checkbox list in JavaScript.

For this purpose, I have written the following code snippet:

    var userType = "";
    var chkBox = document.getElementById('<%=chbUserType.ClientID %>');

    var options = chkBox.getElementsByName('input');
    var listOfSpans = chkBox.getElementsByTagName('span');
    for (var i = 0; i < options.length; i++) {
        if (options[i].checked) {
            if (i != options.length - 1) {
                userType = listOfSpans[i].attributes["JSvalue"].value + ",";
            }
            else {
                userType = listOfSpans[i].attributes["JSvalue"].value;
            }
        }
    }

    alert(userType);

However, when I run this code, I am not seeing any values in the alert. Can someone please guide me on how to achieve this?

Edit 2 :

Generated HTML

<span jsvalue="2"><input id="MainContent_chbUserType_1" type="checkbox" name="ctl00$MainContent$chbUserType$1" value="2"><label for="MainContent_chbUserType_1">Dispatcher</label></span>

Answer №1

Perhaps using the getElementsByTagName method on your input elements instead of getElementsByName will solve your issue...

Check out this jsfiddle link that I believe illustrates your problem

var userType = "";
var chkBox = document.getElementById('checkboxlist');
var options = chkBox.getElementsByTagName('input');
var listOfSpans = chkBox.getElementsByTagName('span');

for (var i = 0; i < options.length; i++) {
    console.log(options[i].checked);
    if (options[i].checked) {
        if (i != options.length - 1) {
            userType = listOfSpans[i].attributes["JSvalue"].value + ",";
        }
        else {
            userType = listOfSpans[i].attributes["JSvalue"].value;
        }
    }
}

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

Automatically trigger a popup box to appear following an AJAX request

I am currently working on a time counter script that triggers a code execution through ajax upon completion. The result of the code should be displayed in a popup box. Below is the code snippet I am using: var ticker = function() { counter--; var t = ...

What is the best way to simulate a CSS import for a jest/enzyme test?

I am facing an issue with mocking an imported CSS file in my jest/enzyme test: Header.test.js import React from 'react' import { shallow } from 'enzyme' import { Header } from './Header' jest.mock('semantic-ui-css/sema ...

I am in possession of a JSON file that lacks keys, and my objective is to extract the values and store them in a C# class object

Here is a JSON sample that I need to parse: [ [ 1617235200000, "58739.46000000", "59490.00000000", "57935.45000000", "58720.44000000", "47415.61722000", 1617321599999, &quo ...

There seems to be a problem as exits.success is not a recognized function -

Currently, I am exploring how to utilize Sails.js with the node-machine-syntax specifically in the context of listing flights. The code snippet below outlines my attempt at achieving this: /** * FlightsController * * @description :: Server-side actions fo ...

A step-by-step guide on retrieving information from Material UI components and incorporating an onSubmit feature to transmit data to the backend server

I've recently started working with react/material-UI. While working on a project, I turned to youtube videos and various resources for guidance. I opted for material-UI due to its user-friendly nature. However, I'm currently facing a challenge ...

JavaScript code to dynamically change the minimum value of an input field when the page

How can I use JavaScript to change the minimum value onload? I tried the following code but it didn't work: <script type="text/javascript">$(document).ready(function(){ $("#quantity_5c27c535d66fc").min('10'); });</script> ...

Unable to properly delete data in Express/Postgres

After developing a Kanban board using JavaScript without any frameworks on the front end, I integrated Express/Postgres on the back end. However, I am encountering an issue with the 'Delete' operation. While all other CRUD operations are functio ...

The data that has been retrieved is not currently displayed within the Vue table

I'm currently exploring js/vue and I'm attempting to retrieve data from an API. There's a field where the value is used to fetch data from the API based on that keyword. When I check the console log, I can see that the data is being received ...

Sometimes LINQ to SQL saves a date without saving the time portion

Strange issue. I am encountering a problem with 3 places/columns where I execute the following code... var order = db.Orders.Where(a => a.OrderID == orderID).First(); order.dateOne = DateTime.Now; db.SubmitChanges(); Everything works fine in this scen ...

What is the best way to refresh a React ES6 component following an AJAX response?

I'm a beginner in React and ES6, trying to create a search field that fetches data as the user types. I want to make an AJAX call using the fetch API when the user types at least 3 characters in the field. When I run the fetch snippet code in the brow ...

Guide on uploading a file to Pinata directly from a React application

I keep encountering the 'MODULE_NOT_FOUND' console error code. Displayed below is the complete console error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f4b4d564b5a4d4d5e4c1251505b5a7f0e110f110f">[email& ...

The resume button is failing to activate any functions

I recently encountered an issue with a JS file that is associated with a Wordpress Plugin, specifically a Quiz plugin featuring a timer. I successfully added a Pause and resume button to the quiz, which effectively pauses and resumes the timer. However, I ...

An error has occurred in the Shadow Dom due to the inability to access the property 'style' of an

While working on a component using shadow DOM, I encountered the following error in the console: "Cannot read property 'style' of undefined". This issue seems to be related to my HTML code in PHP. The main challenge I am facing is figuring out ho ...

Using Commas to Separate ChartJS Data Points

I am having trouble formatting numbers in a ChartJS graph to include commas. For example, my data points are currently displayed as 1032.05, 4334.75, 8482.46 but I need them to show as 1,032.05, 4,334.75, 8,482.46. If you would like to see the current cod ...

Replace HTML elements with AJAX and JavaScript

Working with MySQL data in pyramid presents a challenge as I need to dynamically change an HTML if statement based on the results from JS ajax calls. The main page receives data from views.py and passes it to the .mak script. The key views here are the ma ...

Tips for Utilizing jQuery each Loop

I am attempting to create a foreach loop that will iterate through hidden values on the page, compare them with an external API using Ajax, and display the API results in a < ul > for example. Sample model ITEM1 metavalue (which needs to be che ...

What could be causing the dysfunction of the jQuery class adding function?

I'm new to using jQuery and I'm trying to add a class to the 'a' tag when the 'li' tag is clicked. However, it doesn't seem to be working as expected. $('.nav-item').click( function() { $(".nav-item a").re ...

injecting javascript dynamically using jquery

I am attempting to conditionally load a script in the case that the browser being used is IE8. To achieve this, I have employed jQuery's .getScript function as it allows me to execute certain actions after the script has been loaded. The issue lies in ...

Break up a list into separate paragraphs and style each word using individual CSS

I have a user-generated paragraph that consists of a list of words separated by commas, such as "dog, cat, hamster, turtle." I want to be able to individually assign attributes to each word in the list. Check out this image for reference In the example i ...

The useNavigate() function seems to be failing to redirect to the '/protected' route

The issue lies in the redirection process after receiving the token from the API. Although the token is successfully saved in local memory, the redirect to the intended page does not occur as expected. Instead, a manual window refresh is required to naviga ...