Collect user input from an array of checkboxes

After spending hours attempting to retrieve data from an array of checkboxes with the same name, I am still facing difficulties.

<input type="checkbox" name="node"/>

var selectedValues = [];

             $(document.getElementsByName("node")).each(function () {
            selectedValues.push($(this).checked);
           });

            $.ajax({
                url: "/Summary/Test",
                type: "POST",
                data: selectedValues,
                traditional: true                
            });

public void Test(string [] nodes)
        {
        }

I'm finding it challenging to identify where my mistake lies. Why is it not executing that particular line?

Answer №1

To gather an array of values from checked checkboxes, utilize the mep method like this:

var selectedValues = $('[name=node]:checked').map(function() {
    return this.value;
}).get();

This code assumes you are using jQuery.

If you prefer plain javascript, a similar approach can be taken:

var selectedValues = [],
    nodes = document.querySelectorAll('[name=node]');

Array.prototype.slice.call(nodes).forEach(function(el) {
    if (el.checked) {
        selectedValues.push(el.value);
    }
});

For AJAX functionality:

$.ajax({
    url: "/Summary/Test",
    type: "POST",
    data: {nodes: selectedValues},
    traditional: true             
});

Answer №2

It's important to avoid naming all checkboxes the same, as only the final value will be submitted. Make sure to update each one with:

<input type="checkbox" name="node[]" />

This adjustment will generate an array of the chosen values.

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

Looking for a jQuery Gantt Chart that includes a Treeview, Zoom functionality, and editing capabilities?

I am in need of integrating a dynamic Gantt Chart tool into a room booking solution using jQuery. The Gantt chart should be highly interactive, allowing for drag-and-drop functionality, a tree view on the left to group tasks, and a zoom feature for adjusti ...

The autocomplete feature in Codemirror seems to be failing specifically when writing JavaScript code

I am having trouble implementing the autocomplete feature in my JavaScript code editor using Codemirror. Can someone please help me figure out what I'm doing wrong? Here is the snippet of code : var editor = CodeMirror.fromTextArea(myTextarea, { ...

Ensure UseEffect is only triggered once with specific dependencies

Whenever the component is loaded, I have a method called useEffect() that runs once. useEffect(() => { (async function fetchData() { const results = await stateIsoAPI(); setStates(results); // API results to trigger other Use effect ...

Maintaining Scene Integrity in THREE.JS: Tips for Handling Window Resizing

My layout includes a div with a scene that looks great initially; however, as soon as I start moving or resizing the window, the scene overflows the boundaries of the div and goes haywire, almost filling the entire window. Are there any techniques or solu ...

Set the Vue 3 Select-Option to automatically select the first option as the default choice

I am attempting to set the first select option as the default, so it shows up immediately when the page loads. I initially thought I could use something simple like index === 0 with v-bind:selected since it is a boolean attribute to select the first option ...

The CSS popup box fails to reset its data after being closed, and the closure button does not effectively close the popup

I am having an issue with a login popup on my website. Whenever I fill in the login or registration information and then close the popup, the next time I open it, the input box still contains the previous data. How can I reset the popup to always open with ...

Incorporating Earth Engine scripts into my AngularJS project to showcase NDVI data layer on a Google Map

Is there anyone who has successfully integrated the Earth Engine API into their front-end JavaScript code? I've been attempting to follow the demo on the earth-engine repository to add a layer to a map, but I haven't had any success. It seems lik ...

The Express application fails to receive a response from a Mongodb query function

In my current project, I am implementing a simple API Key authentication system. The main goal is to validate the provided key against the user's input. There is a separate file containing a function that queries the database and returns either true/ ...

Are there any ASP.NET MVC counterparts to JavaScript Generators?

As I transition my application from MonoRail to ASP.NET MVC, I am curious if there is a counterpart to brailjs and njs. In Ruby on Rails, there is a similar concept found in the PrototypeHelper JavaScriptGenerator Methods. While I currently utilize the A ...

Failed to establish Modbus TCP connection

Currently, I am utilizing the "Panasonic FP7" master PLC along with their official software "FPWIN GR7" to monitor data flow on my PC. However, since the software lacks certain functions, I have decided to develop a solution using nodeJS. Below is the code ...

Angular's watch feature fails to trigger when the value is modified

My setup includes two sliders, one for brightness and the other for contrast. They are linked to a "brightness" model and a "contrast" model. These sliders are located within a tab interface, and I noticed that every time the tab was changed, the values we ...

Sending data using jQuery to a web API

One thing on my mind: 1. Is it necessary for the names to match when transmitting data from client to my webapi controller? In case my model is structured like this: public class Donation { public string DonorType { get; set; } //etc } But the f ...

Emphasizing Text Within Div Element

Imagine having a div element structured as such: <div id="test" class="sourcecode"> "Some String" </div> Can CSS and JavaScript be utilized to highlight a specific portion of that string based on a search query? For instance, if the search q ...

Error message: JQuery IAS Infinite Scrolling + Packery - The IASCallbacks function is not declared

I'm having difficulty integrating Packery with Jquery Infinite AJAX scroll on a Tumblr theme. I keep getting the error "Uncaught ReferenceError: IASCallbacks is not defined" and I can't figure out why. Here's the code I've put together ...

What could be causing the href to malfunction on my local website?

I'm currently working on adding a new link that directs to a local HTML website within a menu list on a website. The main website is in ASPX format, but my focus is on the HTML version. The link I want to add leads to an HTML website stored on my loca ...

Altering the input type of a cloned element in Internet Explorer results in the loss of the value

When I have checkbox inputs displayed in a modal with preset value attributes, upon clicking "OK", I clone them and change their input types to hidden, then append them to a div in the document body. However, when trying to retrieve their values using jQue ...

Utilizing dual identifiers in a Jquery plugin

I am currently working with a jQuery plugin and I need to apply the same functionality to two different IDs. How can I achieve this? It involves a next and previous functionality where clicking on the next button automatically scrolls both divs. The issu ...

Executing a custom object function in AngularJS by using the ng-click directive

As I navigate my way through AngularJS, I find myself grappling with the concept of calling a custom method of an object and wonder if there's a simpler approach: https://jsfiddle.net/f4ew9csr/3/ <div ng-app="myApp" ng-controller="myCtrl as myCtr ...

Sending an array encoded in JSON to jQuery

I'm attempting to send an array that I've created in PHP using json_encode(). The process involves running an AJAX request, as shown below: AJAX CALL: $.ajax({ type: "POST", url: "../includes/ajax.php?imagemeta=1", data: ...

In the absence of a value

In my code, I've implemented a functionality that saves the user's input into local storage and displays it in a specific ID. However, I want to make sure that if the input field is left empty, the user is prompted to enter their name. function ...