Looking to extract data from various checkbox options and save it as an array variable

For a coding boot camp assignment, I'm working on a modal that includes options for the days of the week.

My approach involves using Jquery .each and CSS :checked to retrieve the values assigned to each input. However, every time I attempt to log the array I'm pushing to, it returns empty.

This is my first post on StackOverflow, and I'm very new to coding, so please bear with me :)

I apologize for any syntax or formatting errors as I've only been coding for about 1.5 months.

I've tried assigning different IDs to each checkbox and then pulling the values one by one into an array. I also attempted giving them all the same name to utilize the CSS checked feature in combination with .each but neither method seemed to work.

// Below is the checkbox section of the modal //

<div class="form-check form-check-inline">
        <input class="form-check-input" type="checkbox" name="daysOfWeek" value="Monday">
        <label for="Monday">Monday</label>
      </div>
      <div class="form-check form-check-inline">
        <input class="form-check-input" type="checkbox" name="daysOfWeek" value="Tuesday">
        <label for="Tuesday">Tuesday</label>
      </div>
      <div class="form-check form-check-inline">
            <input class="form-check-input" type="checkbox" name="daysOfWeek" value="Wednesday">
            <label for="Wednesday">Wednesday</label>
    </div>
    <div class="form-check form-check-inline">
            <input class="form-check-input" type="checkbox" name="daysOfWeek" value="Thursday">
            <label  for="Thursday">Thursday</label>
    </div>
    <div class="form-check form-check-inline">
            <input class="form-check-input" type="checkbox" name="daysOfWeek" value="Friday">
            <label  for="Friday">Friday</label>
    </div>
    <div class="form-check form-check-inline">
            <input class="form-check-input" type="checkbox" name="daysOfWeek" value="Saturday">
            <label  for="Saturday">Saturday</label>
    </div>
    <div class="form-check form-check-inline">
            <input class="form-check-input" type="checkbox" name="daysOfWeek" value="Sunday">
            <label for="Sunday">Sunday</label>
    </div>
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" name="daysOfWeek" value="Weekday">
      <label for="Weekday">Weekday</label>
    </div>
    <div class="form-check form-check-inline">
    <input class="form-check-input" type="checkbox" name="daysOfWeek" value="Weekend">
    <label  for="Weekend">Weekend</label>
    </div>


// Here is where the attempt to call back the values of the checked boxes is made //

$("#submitButton").on("click", function () {
    event.preventDefault();
            var  daysOfWeek = [];
                  $.each($("input[name='dayOfWeek']:checked"), function(){
                    daysOfWeek.push($(this).val());
                  });

      console.log(daysOfWeek)

    });

I am hoping to receive an array containing the values (set of strings) entered for each checkbox option and be able to store and console.log it. Currently, I'm only receiving an empty array.

Answer №1

To simplify even further, you can use the map method and then convert it into an array by utilizing spread syntax:

$("#submitButton").on("click", function() {
  event.preventDefault();
  var daysOfWeek1 = [...$("input[name='daysOfWeek']:checked").map((i, el) => $(el).val())];
  console.log(daysOfWeek1)
});
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div class="form-check form-check-inline">
  <input class="form-check-input" type="checkbox" name="daysOfWeek" value="Monday">
  <label for="Monday">Monday</label>
</div>
<div class="form-check form-check-inline">
  <input class="form-check-input" type="checkbox" name="daysOfWeek" value="Tuesday">
  <label for="Tuesday">Tuesday</label>
</div>
<div class="form-check form-check-inline">
  <input class="form-check-input" type="checkbox" name="daysOfWeek" value="Wednesday">
  <label for="Wednesday">Wednesday</label>
</div>
<div class="form-check form-check-inline">
  <input class="form-check-input" type="checkbox" name="daysOfWeek" value="Thursday">
  <label for="Thursday">Thursday</label>
</div>
<div class="form-check form-check-inline">
  <input class="form-check-input" type="checkbox" name="daysOfWeek" value="Friday">
  <label for="Friday">Friday</label>
</div>
<div class="form-check form-check-inline">
  <input class="form-check-input" type="checkbox" name="daysOfWeek" value="Saturday">
  <label for="Saturday">Saturday</label>
</div>
<div class="form-check form-check-inline">
  <input class="form-check-input" type="checkbox" name="daysOfWeek" value="Sunday">
  <label for="Sunday">Sunday</label>
</div>
<div class="form-check form-check-inline">
  <input class="form-check-input" type="checkbox" name="daysOfWeek" value="Weekday">
  <label for="Weekday">Weekday</label>
</div>
<div class="form-check form-check-inline">
  <input class="form-check-input" type="checkbox" name="daysOfWeek" value="Weekend">
  <label for="Weekend">Weekend</label>
  <button id="submitButton">Submit</button>
</div>

Answer №2

Oops! It seems everything is functioning properly - I mistakenly used dayOfWeek below and daysOfWeek above...

.>

Apologies for the confusion.

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

Uploading files asynchronously with AJAX in Laravel

For the past couple of days, I've been attempting to make ajax file uploads work in Laravel 4, but unfortunately, I haven't had any success. This is my jQuery code: $(document).ready(function(){ $('#basicModuleImage').change(function ...

Step-by-step tutorial for making a mesmerizing fade out grunge background

How can I achieve a fading grid background effect? I have experimented with using a conic-gradient for the background, but I am unsure how to make it fade out. background: conic-gradient(from 90deg at 1px 1px,#0000 90deg,grey 0) 0 0/50px 50px; ...

Incorporate h:outputText into your JavaScript code segment

After populating some information into a h:outputText, I am now looking to trigger a JavaScript function upon clicking a button that will retrieve the text from the outputText. The structure of the code is as follows: <p:tabView id="tabView"> & ...

Can you explain the distinction between JQuery and a jQuery Plugin?

There seems to be a bit of confusion around whether it's called simply JQuery or JQuery Plugin. After doing some research, I couldn't find a clear explanation on whether they are the same thing. Can you shed some light on this? ...

How can we effectively reroute HTTP requests according to the information stored in a database?

When operating an express server, what is the appropriate method for redirecting incoming requests? In my application, I have two routes: POST and UPDATE. The POST route is responsible for creating a new item in the database, while the UPDATE route increa ...

Guide to connecting two geometric shapes together with the help of three.js

Is there a way to link two spheres together with a line? I'm looking for a solution that mimics two balls connected by a rope or something elastic. Does anyone have any examples to share? ...

Combining two different arrays in JavaSscript to create a single array

I have two arrays, one representing parents and the other representing children in a relational manner. I need to combine these into a single array. Parent array: const cat = ['a','b','c']; Child array: const sub =[{name:&ap ...

Is Window.navigator malfunctioning on different browsers in Mac OS?

I'm attempting to access the navigator function in my project to share a specific URL, but I'm facing difficulties accessing it on Mac OS when using browsers other than Safari. Is there a solution to this issue? Below is the function I created f ...

Securely transmit ID values through ajax calls

Picture this: I have a website where users' profile pages are accessed through addresses like the following: http://www.samplewebsite.com/profile.php?p=123 Now, I want to be able to block or perform another action on a user when I click a button. To ...

The jQuery UI Dialog is experiencing an issue with a button that is triggering a HierarchyRequest

I am facing an issue with a piece of javascript that works perfectly on other pages but is now throwing a HierarchyRequestError on a new page. This leads me to believe that there may be an HTML problem on this particular page. Here is a simplified version ...

Creating separate versions (development and production) of JavaScript code: a step-by-step guide

I have been working on a small web application that is distributed in a Docker container, using an nginx image. This application consists of plain html and js code, without any frameworks. Within the JS code, there is access to a remote host via WebSocket ...

Node.js - Error: JSON.Parse and JSON.Stringify are not recognized as functions

Is it possible to convert a string to JSON and vice versa without any additional npm packages? I am currently using JSON.Stringfy in my router.js file. Are there any specific npm modules that need to be added to the project in order to use the JSON.Stringf ...

Console log displays varied outputs for identical arrays

Having an array in a static form and one that is filled using the ajax post function, I initially planned to replace the static array with the dynamic one. However, upon closer inspection, it seems that the two arrays are not matching. Array 1 (static) ...

Fade in and out on button press

There is a button with the following HTML code: <input type="submit" id="btnApply" name="btnApply" value="Apply"/> Upon clicking the button, a div should be displayed. <div> Thanks for applying </div> The display of the div should fade ...

What is the best way to align a dropdown menu and a textbox on the same line

I have recently been working on a search bar that includes a Dropdown for Location and a Textbox for Search. Prior to implementing bootstrap, these elements were displayed in a single line. However, after applying bootstrap, they are now stacked vertically ...

Encountering issues with Stylus when trying to compile the `@font-face

I'm diving into the world of CSS compilers with Stylus for the first time, and I'm facing an issue with loading Google Web Font URLs correctly. Below is the code snippet causing trouble: @font-face { font-family: 'Roboto'; font-st ...

Utilizing Vue Store Methods within an Array or Object

Imagine we have 5 identical buttons. Instead of duplicating them, I decided to make use of v-for. methods: { a() {}, b() {}, ... } Replacing the individual buttons with: <v-btn block color="primary" class="my-1" @click="a">A</v-btn ...

Guide on establishing a connection with a TCP server and sending a JavaScript script to it

I am completely new to JS and node. I am using SkyX Pro, a telescope management software that has the capability to run a TCP Server on port 3040. By connecting with Netcat and providing it with Javascript starting with //* Javascript *//, I can control ca ...

Exploring the method of extracting multiple checkbox values from an HTML form

While I'm aware that jQuery can be used to retrieve checkbox values when there are multiple checkboxes, the solutions available online don't seem to work for me. This is because my checkbox inputs are embedded within an HTML form, and none of the ...

Generate code in Yii2 using the active form

This is the code I am using in Yii2: <?= $form->field($model, 'username')->label(false); ?> <?= $form->field($model, 'password')->label(false); ?> It produces the following output: <div class="form-group fi ...