0

I've 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: []
}

My output is this = [ ]

But I want to achieve this:

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

And if I click again into a checkbox field the jsonstring have to 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 my problem.

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
3
  • 2
    Trying to build a JSON string yourself is quite sensitive to errors, it's better to use JSON.stringify and JSON.parse for that purpose and just build regular JS objects and arrays instead. Commented Jan 8, 2016 at 8:49
  • Try to trigger the function when the input is onclick jsfiddle.net/w0wyrp2z Commented Jan 8, 2016 at 8:51
  • You're logging when the function is called, not when the user clicks on the boxes. Commented Jan 8, 2016 at 10:45

3 Answers 3

3

You could try something like so:

var uncheckedFilters = [];

function generateJSONstringforuncheckedfilters(){
    $('body').on('click', 'input', function() {
        var checkboxSelector = $(this);
        var checkboxFilterGUID = checkboxSelector.attr('data-filterguid');
        if(checkboxSelector.is(':checked')) {
            uncheckedFilters.forEach(function(filter) {
                if(filter.FilterGUID === checkboxFilterGUID) {
                    var 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 way you are generating an array of filter objects which you could simply convert to json using JSON.stringify like in my example above.

JSFiddle: https://jsfiddle.net/7j4g0ddb/

Sign up to request clarification or add additional context in comments.

1 Comment

I would just add something like: $(this).addClass("registred") and check if hasClass so I don't register the same input more than once
1

try this

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


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

3 Comments

That works with one input checkbox.. But I have a lot of. If I click the first checkbox and uncheck THIS checkbox again the jsonstring contains the same. That is not correct for me.
Now I get all checkboxes in the jsonstring with one click.
@cgee added the check for checked checkboxes
0

First, for information, all element are juste one similiar Id on your HTML document (you can see W3C normes for that) it's for your HTML Code :

<input type="checkbox" checked="checked" id="check1" value="volladressierbar" />
<input type="checkbox" checked="checked" id="check1" value="teiladressierbar" />
<!--  Id of both Elements is similar -->

That is correct :

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

Also, you can check that for the javascript code:

$('body').on('click', 'input', function(){
        var arrayJson = [];
        // get all input checked
        $( '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 with all data input getted.
        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
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.