Using jQuery to combine the values of text inputs and checkboxes into a single array or string

I need to combine three different types of items into a single comma-separated string or array, which I plan to use later in a URL.

Is there a way to merge these three types of data together into one string or array?

  1. An existing POST string
  2. User input from a text field with an Add button
  3. The values of multiple checkboxes

Currently, the code I have only allows me to add form input values, and I'm struggling to remove a checkbox value from the string when its box is unchecked.

Here's the fiddle.

This is the HTML structure being used:

<div class="srs-display">existingPostString</div>

<ul id="srs" class="srs">
    <!-- START TEXT INPUT FIELD -->
    <li class="sr">
        <div class="masonry-well">
            <input id="sr-custom" type="text" placeholder="Add your own">
            <a class="add-sr-custom">Add</a>
        </div>
    </li>
    <!-- END TEXT INPUT FIELD -->
    <!-- START CHECKBOXES -->
    <li class="sr">
        <div class="masonry-well">
            <input id="srPredefined1" type="checkbox" name="srPredefined1" value="srPredefined1">
            <label for="srPredefined1" class="ts-helper">srPredefined1</label>
        </div>
    </li>
    <li class="sr masonry-item">
        <div class="masonry-well">
            <input id="srPredefined2" type="checkbox" name="srPredefined2" value="srPredefined2">
            <label for="srPredefined2" class="ts-helper">srPredefined2</label>
        </div>
    </li>
    <li class="sr masonry-item">
        <div class="masonry-well">
            <input id="srPredefined3" type="checkbox" name="srPredefined3" value="srPredefined3">
            <label for="srPredefined3" class="ts-helper">srPredefined3</label>
        </div>
    </li>
    <!-- END CHECKBOXES -->
</ul>

Below is the JavaScript code that has been attempted so far:

$('input[type="checkbox"]').bind('change', function() {
    var srs = 'existingPostString';

    $('input[type="checkbox"]').each(function(index, value) {
        if (this.checked) {
            /*add*/ /*get label text associated with checkbox*/
            srs += ($(this).val() + ', ');
        }
    });
    if (srs.length > 0) {
        srs = srs.substring(0,srs.length-2);
    } else {
        srs = 'No checks';
    }

    $('.srs-display').html(srs);
});

$(".add-sr-custom").on('click', function() {
    var srs = 'existingPostString';

    srs +=  ',' + $('#sr-custom').val();
    $('.srs-display').text(srs);
})

Answer №1

To store the string values into an array, you can simply loop through each element and push it to the array. Afterwards, you can use the join() method on the array to concatenate them with a comma separator. Here's an example:

var strings = [];
// iterate over each checkbox
strings.push($(this).val());

// at a later point
var concatenated_string = strings.join(',');

Answer №2

Hey there, take a look at this solution:https://jsfiddle.net/leojavier/onwkaLet/6/

var selectedCheckboxes = [];

    $('input[type="checkbox"]').bind('change', function() {
         selectedCheckboxes=[]
        $('input[type="checkbox"]').each(function(index, value) {
            if (this.checked) {
                selectedCheckboxes.push($(this).val());
            }
        });

        $('.selected-checkboxes-display').html(selectedCheckboxes);
    });

    $(".add-selected-custom").on('click', function() {
        $('#custom-selected-checkboxes').val(selectedCheckboxes);
    })

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

Assist me in minimizing redundant code in a basic jQuery function

I successfully created a carousel using the jQuery cycle plugin with 4 links that correspond to different slides. Currently, I have separate blocks of code for each link, but I'm looking to optimize by creating a single function. $('#features-sl ...

The ajax method for loading an xml file results in displaying the undefined message

When attempting to fetch content from an xml file using ajax, the page initially displays "undefined". However, upon refreshing the page, the content loads successfully. Take a look at my code snippet below: $.ajax({ type: "GET", url: "xm ...

Struggling with routing in Node.js while working on REST API development via HTTP

I am facing an issue while trying to complete a MEAN project. The client side is already done, but I am having trouble with the server side when attempting to make a new insertion (which is carried out using HTTP Post). Below, I will demonstrate how I hav ...

Why are the buttons on my HTML/JavaScript page not functioning properly?

I have been struggling with a code for a 5 image slideshow where the NEXT and PREVIOUS buttons are supposed to take me to the next and previous slides. However, when I press them, nothing happens. Can anyone provide some assistance? I need additional detai ...

How can I send a file and a string request using the POST method to a Spring REST controller that accepts byte[] and Strings with Angular

Need help with sending a post method that includes a file and another string request parameter to a spring rest controller using angular. The server controller parameter is set up to receive an array of bytes for the file and another string request wrappe ...

Incorporate a background image with the JavaScript CSS property

I'm having trouble adding a background image using the Javascript CSS property in my code. When I directly add the 'url', it works fine. Could the issue be with the 'weatherImage' variable? Javascript var OpenWeatherKey = ' ...

What issues can arise in JavaScript if the URL length is not zero when there is no match found?

Upon clicking the "Open Windows" button in Code A, I expected the two links to open in two tabs simultaneously in Chrome, which is exactly what happened. However, when I added a blank line in the textarea control in Code B, only the link http:// ...

Transform the binary image data sent by the server into an <img> element without using base64 encoding

It's been a challenge trying to find a reliable method for adding custom request headers to img src, so I'm experimenting with manually downloading the image using ajax. Here is an example of the code I am working on: const load = async () => ...

Interacting with an API and retrieving data using JavaScript

I have hit a roadblock. This question might be simple, but I am struggling to figure it out. I am attempting to retrieve a response from an API (mapquest), but I can't seem to navigate the response to extract the necessary information. Here is my con ...

Issues arise with Ninja Forms when attempting to integrate with jQuery 3.1.1

I have integrated jQuery 3.1.1 into one of our websites to support the Slick slider feature. However, after updating WordPress with the latest jQuery version, the conditional logic on the form stopped functioning properly. Ninja Forms insists that the iss ...

Unable to save cookies on mobile browsers, but functioning properly on desktop computers

Currently, I am facing an issue with my ExpressJS app hosted on Heroku and a frontend React app hosted on Netlify. The problem arises when a user logs in successfully and is directed to the home page showing personalized content. Upon landing on the home p ...

Empty jQuery $.ajax value after post

I'm encountering an issue where my code's post value appears to be empty. I have attempted to echo the key and value using a foreach loop, but it only shows "0 Array." This is what my code looks like: <script type="text/javascript"> $(doc ...

SetBootstrapTooltip at the location of the mouse pointer

Is it feasible to implement a bootstrap tooltip that follows the mouse cursor in AngularJS? If not, what other options are available for achieving this functionality? ...

Error encountered: Provider '$rootScopeProvider' is not recognized - check for typos in the syntax

I am encountering an issue with the templateUrl in AngularJS. When I input this code into my editor and execute it, everything works flawlessly: HTML: <!DOCTYPE html> <html lang= "en"> <head> <meta charset="UTF-8" /> < ...

Create a responsive Flexslider with a dynamic background image

Has anyone experienced issues with creating a responsive design while working with flexslider and background images? I tried placing contents inside li tags with background images, but it seems to break the slider's responsiveness. Here is the code sn ...

Triggering a re-render in React

There are times when I find myself needing to trigger a re-render while still in the middle of executing a function. As a solution, I've developed a method using the state variable my_force_update. Basically, I change it to a random value when I want ...

Utilizing React for handling data exchange between child and parent components

I am still learning about React and material-ui, and I am exploring how to pass data from a child component to a parent component to update the parent state. Currently, when I try to update the state with a new date, it is being logged in the console but t ...

Dynamic creation of HTML/Ionic checkbox leads to ng-change not binding properly

Recently, my team and I have been actively engaged in the process of handling an XML file and dynamically constructing a settings page based on the information extracted from it. Allow me to present an illustration of how these elements are dynamically cre ...

Is there a way to consistently apply default props to a styled component?

Currently, I am working with React, Material UI, and Styled Components. My goal is to create a personalized Input field where the size='small' is always passed as a prop to my component. To clarify, if the user neglects to include the size attri ...

How can I change the transparency of a CSS background color using JavaScript?

I have a question about CSS: .class1 { background: #fff } Now, I need to achieve the following: .class2 { background: rgba(255,0,0,0.5) }; Is there a way to use JavaScript only to change the background property of .class1 and give it an opacity of 0.5? ...