Having trouble retrieving the values of checked items in checkboxlist using JavaScript

Within my application, there is a checkbox list. The following HTML code showcases the structure of the checkbox list along with the VB code responsible for binding it upon loading the respective page.

<asp:CheckBoxList Runat="server" id="chklistTeams" RepeatColumns="7" RepeatDirection="Horizontal"
                        CellPadding="4" Font-Size="7pt"></asp:CheckBoxList>

Below is the VB code used to bind the checkbox list:

myCmd.CommandText = "Select id, title from teams"
Dim DS As SqlDataReader
DS = myCmd.ExecuteReader
chklistTeams.DataValueField = "id"
chklistTeams.DataTextField = "title"
chklistTeams.DataSource = DS
chklistTeams.DataBind()
DS.Close()

Upon clicking the save button, a JavaScript function is triggered. Here is a snippet of that function which aims to retrieve the values of the items:

var checkList = document.getElementById('chklistTeams');
var checkBoxList = checkList.getElementsByTagName("input");
var checkBoxSelectedItems = new Array();

for (var i = 0; i < checkBoxList.length; i++) {
    if (checkBoxList[i].checked) {
        checkBoxSelectedItems.push(checkBoxList[i].value);
        alert('checked - checkBoxList[i]: ' + checkBoxList[i].value)
    }
}

Despite storing values in the array, all retrieved values show as "on" upon testing (as confirmed by the alert). Upon inspecting the HTML of the checkboxes, one entry appears as follows:

<input name="chklistTeams:21" id="chklistTeams_21" type="checkbox" value="on"/>

The previous VB code accurately fetched integer values for checked items. However, our current requirement mandates fetching these values via JavaScript due to restrictions on using PageMethods with a public shared function on the backend.

Kindly advise on why the JavaScript method returns "on" instead of the integer values like the VB approach. Appreciate any assistance provided. Remember, JS must be used, and the VB method cannot be utilized due to its public shared nature. Thank you.

Answer №1

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkboxlist.aspx

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.items.aspx

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listitem.aspx

It is worth noting that the checkboxlist.items(index) belongs to the listitem type. Listitem comes with an attributes property which allows setting client-side attributes.

Here's a code example you can refer to: ListItem.Attributes.Add not working

For your specific situation within the chklistTeams DataBound event:

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

In JavaScript notation:

checkBoxSelectedItems.push(checkBoxList[i].getAttribute("JSvalue"));

Answer №2

After facing this issue, I devised a solution by creating a global shared array. Upon loading, I filled the array with the id values. Then, using JavaScript, I managed to determine the index of the selected items - allowing me to access the corresponding id value from the array for future reference.

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

Efficient method for retrieving the values of each cell in a row within an array

I've got a standard table here - 6 columns, multiple rows, all filled with data. Right now, my goal is to collect all this table data into an array: tableData(0) = "1, Hans, Testperson, Munich, Germany" tableData(1) = "2, Petra, Tes ...

Using two indexes in ngFor can result in unexpected changes to the values being displayed

I am currently working on printing checkboxes and facing an issue with initializing the id and name attributes using ngFor. The values I'm getting are incorrect. Let's consider 2 arrays (or n arrays retrieved from a database): animal = 'do ...

Using Javascript to dynamically copy text to the clipboard

Is there a way to create a function that can automatically copy the current URL in the address bar to the clipboard? Before jumping to conclusions, hear me out: I'm looking for a solution where the copying process happens dynamically, not just when ...

jquery's advanced selector fails to find a match

I am encountering an issue with my code where it doesn't seem to work even though I have three IDs in the DOM. Strangely, there is no error message being displayed. $(function() { console.log('test') $('[div][id*="sohai"]').e ...

Determine the cumulative and present slide count on the Bootstrap slider

Using JavaScript and Bootstrap controls, you can easily track the number of slides in a standard Bootstrap carousel. By implementing a simple button press counter that increments or decrements, you can keep track of the total and current slide numbers usin ...

Extract information from Firebase and display it in a React component

I am trying to extract and display data retrieved in componentDidMount. Here is the state setup: constructor(props) { super(props); this.state = { loading: true, data: [] } } and here is the componentDidMount function: compo ...

What are the differences between a Chrome app and extension? Is there any other way to access the tabs currently open in your

I need to develop an app that can access the tabs a user has open, but I'm struggling to find a way to do so without having my app run in Chrome itself. Creating an extension restricts the UI significantly, which is problematic since my app requires a ...

Creating a new list by grouping elements from an existing list

I have successfully received data from my API in the following format: [ {grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, type: "Type_1"}, {grade: "Grade B", id: 2, ifsGrade: &quo ...

Tips for disabling Bootstrap dropdown's preventDefault function- Ways to remove preventDefault

I have incorporated the Bootstrap 3 dropdown menu into my code, but I want it to pop out when I hover over the elements instead of the default behavior. To achieve this, I wrote a small script: jQ('.dropdown').hover(function() { jQ(this).fin ...

Combining Vueify with Elixir and Hotloading led to an unexpected error: Uncaught TypeError - property 'indexOf' is undefined

I have successfully configured Elixir to utilize Vueify with a hot reload plugin. The compilation process runs smoothly, but I encounter a console error in my compiled file and the Vue component does not seem to transform into HTML; it still displays the & ...

Having trouble accessing the URL route by typing it in directly within react-router?

Having some trouble getting dynamic routes to work with react router. Whenever I enter a URL like localhost:3000/5, I receive the error message "cannot GET /5". Here is how my router is configured: class App extends Component { render() { retu ...

A method designed to accept an acronym as an argument and output the corresponding full name text

Having trouble with my current task - I've got an HTML file and external JS file, and I need a function that takes an element from the 'cities' array as input and returns a string to be used in populating a table. I've set up a functio ...

What is the best way to combine two responses and then convert them into a promise?

When making two calls, the firstCallData prints data fine. However, when I use + to merge the responses, it returns me the following Response. What is a better approach to achieve this task? main.ts let data = await this.processResponse(__data.Detail ...

"Utilizing Material-UI in React to create a textfield input with number validation

I am currently working on an input field that should only accept values within a specified range of min and max. However, I have encountered an issue where manually entering a number bypasses this control mechanism. Is there a way to prevent this from happ ...

What is the best way to import modules in Typescript/Javascript synchronously during runtime?

I have a Typescript class where I am attempting to perform a synchronous import, however, the import is being executed asynchronously. My code snippet looks like this: --------------100 lines of code-------------------- import('../../../x/y/z') ...

Error message: The property or method "Name" is not defined on this object, but it is being referenced during the rendering process

Currently facing a challenge in implementing the modal closure functionality within the Vue.js template. Take a look at the code snippet: var modalInstance = new Vue({ el: "#modalInstance", data: { displayModal: false } }); Vue.compo ...

Explore creating a dial number using React

Hey there, I'm currently working on developing a component. Just to clarify, I am not using react-native for this project. Instead, I would like to utilize React to scroll a number similar to how an image scrolls. https://i.sstatic.net/c1Tu8.png Th ...

Is there a way to maintain data from a database when making another GET request with a different query string in React (Next.js)?

English isn't my first language, so please bear with me! Please review my code first: export default function DriveFolder() { const [clickFolderPk, setClickFolderPk] = useState(1); const viewFolder = async () => { const url = `/ ...

Unable to retrieve the value from the selected radio button

Below is the provided HTML: <form> <div class="form-group"> <div class="checkbox-detailed male_input"> <input type="radio" name="gender" id="male" value="male"> <label for="male"> ...

Sort and filter columns in jQuery datatable

My testing involved setting up a small grid to experiment with the JQuery DataTable column filter. However, upon running the site, I noticed that both the grid header and the row containing the input fields had the sorting class attribute. The versions of ...