You can update a JavaScript string by adding values using the '+=' operator

I have the following function:

function generateJSONstringforuncheckedfilters(){
    jsonstring = '';
    jsonstring = "[";
    $('body').on('click', 'input', function(){
        jsonstring += "[{'OrderGUID': '"+ $(this).attr('data-orderguid') +"' 'FilterGUID': '"+ $(this).attr('data-filterguid') +"', 'nValue': 0, 'Value': '"+ $(this).attr('value') +"', 'Operator': 'NULL', 'Unit': 'NULL'}";
    });
    jsonstring += "]";
    console.log(jsonstring); // Output: []
}

The current output is this = [ ]

However, my desired output is:

[{'OrderGUID': '46dd8c82-44a6-4dc5-9517-320c31645211' 'FilterGUID': '17caabea-c313-48c9-b965-739ef8d09a1f', 'nValue': 0, 'Value': 'volladressierbar', 'Operator': 'NULL', 'Unit': 'NULL'}]

If I click again into a checkbox field, the jsonstring should expand like this:

[
{'OrderGUID': 'aaaaaa' 'FilterGUID': '17caabea-c313-48c9-b965-739ef8d09a1f', 'nValue': 0, 'Value': 'volladressierbar', 'Operator': 'NULL', 'Unit': 'NULL'},
{'OrderGUID': 'bbbbbb' 'FilterGUID': '17caabea-c313-48c9-b965-739ef8d09a1f', 'nValue': 0, 'Value': 'volladressierbar', 'Operator': 'NULL', 'Unit': 'NULL'}
]

I hope you understand the issue I am facing.

Edit:

These are my checkboxes:

<input type="checkbox" checked="checked" id="check1" value="volladressierbar" name="volladressierbar" data-filterguid="17caabea" data-orderguid="aaaa" count="1"> volladressierbar
<input type="checkbox" checked="checked" id="check1" value="teiladressierbar" name="teiladressierbar" data-filterguid="18cagbea" data-orderguid="bbbb" count="1"> teiladressierbar

Answer №1

Consider attempting the following approach:

let uncheckedFilters = [];

function createJSONStringForUncheckedFilters(){
    $('body').on('click', 'input', function() {
        let checkboxSelector = $(this);
        let checkboxFilterGUID = checkboxSelector.attr('data-filterguid');
        if(checkboxSelector.is(':checked')) {
            uncheckedFilters.forEach(function(filter) {
                if(filter.FilterGUID === checkboxFilterGUID) {
                    let filterIndex = uncheckedFilters.indexOf(filter);
                    if(filterIndex > -1) {
                        uncheckedFilters.splice(filterIndex, 1);
                    }
                }
            });
        } else {
            uncheckedFilters.push({
                OrderGUID: checkboxSelector.attr('data-orderguid'),
                FilterGUID: checkboxFilterGUID,
                nValue: 0,
                Value: checkboxSelector.attr('value'),
                Operator: 'NULL',
                Unit: 'NULL'
            });
        }
        console.log(JSON.stringify(uncheckedFilters));
    });
}

This method will help you build an array of filter objects that can be easily converted to JSON by using JSON.stringify as demonstrated in the sample provided above.

JSFiddle: https://jsfiddle.net/9k2gnfxw/

Answer №2

give this a shot

  $('body').on('click', 'input', function(){
    var jsonStr = '';
    jsonStr = "[";
     $( 'body' ).find( "input[type='checkbox']:checked" ).each( function(){
       jsonStr += generateJSONStringForUncheckedFilters( $( this )  ) ;        
     } );
     jsonStr += "]";
     console.log(jsonStr);   
  });


function generateJSONStringForUncheckedFilters( $thisObj ) 
{
       return "{'OrderGUID': '"+ $thisObj.attr('data-orderguid') +"' 'FilterGUID': '"+ $thisObj.attr('data-filterguid') +"', 'nValue': 0, 'Value': '"+ $thisObj.attr('value') +"', 'Operator': 'NULL', 'Unit': 'NULL'}";       
}

Answer №3

Initially, it's important to note that all elements have a unique ID in your HTML document (refer to the W3C standards for more information). Here is an example from your HTML code:

<input type="checkbox" checked="checked" id="check1" value="volladressierbar" />
<input type="checkbox" checked="checked" id="check1" value="teiladressierbar" />
<!-- Both elements have similar IDs -->

To resolve this issue:

<input type="checkbox" checked="checked" id="check1" value="volladressierbar" />
<input type="checkbox" checked="checked" id="check2" value="teiladressierbar" />

Furthermore, ensure the uniqueness of IDs in your JavaScript code as well:

$('body').on('click', 'input', function(){
        var arrayJson = [];
        // Retrieve all checked inputs
        $( 'body' ).find( "input[type='checkbox']:checked" ).each( function(){
            var recupObject = "{'OrderGUID': '"+ $(this).attr('data-orderguid') +"' 'FilterGUID': '"+ $(this).attr('data-filterguid') +"', 'nValue': 0, 'Value': '"+ $(this).attr('value') +"', 'Operator': 'NULL', 'Unit': 'NULL'}";
            arrayJson.push(recupObject);
        });

        // Create a JSON object with the input data.
        if (arrayJson.length > 0){
            var jsonOutput = "[";
            for (index = 0; index < arrayJson.length; index++) {
              jsonOutput += arrayJson[index] + ",";
            }
            jsonOutput = jsonOutput.substring(0, jsonOutput.length-1); // Remove last ','
            jsonOutput += "]";
        }
        console.log(jsonOutput ); // Log the JSON output
    });

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

Issue with CoffeeScript and three.js: scene not defined

I've been troubleshooting this issue for hours, but I can't seem to figure out the error... Here's the error message I'm getting: Cannot read property 'add' of undefined Below is my coffeescript code file (hopefully it&apos ...

Locate a specific data point within an array of JSON objects

After receiving an array of JSON objects from JSP, I now have a set of data that contains book titles. "Titles":[ { "Book3" : "BULLETIN 3" } , { "Book1" : "BULLETIN 1" } , { "Book2" : "B ...

Developing a jQuery Plugin to Generate an Interactive Dropdown Menu

I have a task to dynamically create a select list in which users can add options after the select list has been created. Check out my code snippet below: <script type="text/html" id="select_field"> <div class='row& ...

Tips for sending a changing mouse scroll value as a property in VueJS

I am currently utilizing the Laravel - VueJS framework. My goal is to detect the Y position of the mouse scroll and pass it dynamically as a prop to a Navbar component. To achieve this, I set up an eventListener and stored the window.scrollY value in a va ...

Exploring the power of Next.js dynamic routes connected to a Firestore collection

Currently seeking a solution to create a dynamic route that will display each document in a Firestore collection using Server-side Rendering. For instance, if there is a document named foo, it would be accessible at test.com/foo under the [doc] page compo ...

Does AngularJS have a feature similar to jQuery.active?

As I utilize selenium to conduct tests on my application, I am encountering numerous ajax calls that utilize $resource or $http. It would be convenient if there was a method in angular to monitor active ajax requests so that selenium could wait until they ...

I am in search of a regular expression to validate a Jordanian phone number, whether it includes the country code or not

Looking for a regex pattern that can validate phone numbers beginning with either 0096279, 0096278, 0096277, or 079, 078, 077. ...

Forcing the Empty Table message in jQuery DataTables post an AJAX request

My configuration for jquery-datatables includes a custom search filter that acts as both the standard keyword filter and a specific Item ID search using an ajax call to retrieve a value from the back end, which is then used to search a particular column in ...

When using Angular 2, the array.splice() function is causing the elements to be removed from the

I am currently working with an HTML table that has default checked rows. <table> <tr> <th></th> <th>Id</th> <th>Name</th> <th>Initial</th> </tr> ...

Display or conceal fields depending on custom object specifications

I am attempting to centralize my show/hide functionality for fields in one object (like vm.foo) that contains key-value pairs. For example, I could add another pair like 1502: true to hide a field with the key 1502. Is there a way to pass variables from t ...

Vue component architecture

Just started exploring Vue last night, so the answer might be obvious. I came across components with this layout: <template> <Slider v-model="value"/> </template> <script> import Slider from '@vueform/slider' ...

What is the best way to select the enclosed <a> tag within an <li> element?

Below is the JavaScript code I have attempted: $('#footer').find('.browse li').click(function(e){ $(this).find('a').click(); }); Here is the relevant HTML: <div id="footer" class="span-24"><div ...

Tips for transforming the input date value from Mui Datepicker

import * as React from "react"; import moment from "moment"; import TextField from "@mui/material/TextField"; import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs"; import { LocalizationProvider } from &quo ...

Is it possible for node-java to accept anonymous functions as parameters in Java?

I am looking to pass an anonymous function from JavaScript to Java using node-java (https://github.com/joeferner/node-java). Below is a snippet of the Java code for reference: public class Example { public Example() { } public interface Callb ...

Evaluating string combinations in JavaScript using valid comparisons

After choosing values on the screen, two variables store their value. var uval = '100'; var eval = '5'; There are 2 combinations with values: let combination1= 'u:100;e:1,4,5,10' let combination2 = 'u:1000;e:120,400,500, ...

Struggling to display Three.js ply file on screen

I'm having trouble displaying my ply file using the three.js webgl_loader_ply example. Even though I can view the object in MeshLab when I open the ply file, it doesn't show up in the three.js example. I've tried various adjustments like zoo ...

Invoking two asynchronous functions in React, where the first function relies on the state modified by the second function

Currently, I am working on an app that utilizes the Geoapify API. Within this app, I have implemented three primary API functions. Users are presented with two options on the user interface: they can manually search for cities or utilize their current loca ...

Utilize Nifi's Execute Script Processor with Groovy to perform automated data transformation

I am seeking a solution to dynamically modify the date format of my JSON file before sending it. import groovy.json.* def ff = session.get() if(!ff) return ff = session.write(ff, {rawIn, rawOut-> //parse flowfile content to maps & arrays d ...

Transforming a JSON file that has been previously converted to an Observable into a TypeScript map within an Angular application

There is a json data file named dummy, with the following structure: [ {"key":"KEY1", "value":["alpha","beta","gamma"]}, {"key":"KEY2", "value":["A","B","C"]}, {"key":"KEY3", "value":["One","Foo","Bar"]} ] The goal is to convert this json f ...

How to eliminate the comma from the final element in a JavaScript Vue.js array?

I'm looking to remove the comma from the last element in Vue, but I'm unsure how to do so since the index of the last element is unknown. <td v-if="category.sub_category.length > 0"> <template v-for=&q ...