Search code examples
javascriptcheckboxvisual-studio-lightswitchlightswitch-2013

using checkboxes and counting them in Lightswitch HTML


I am currently using this code to display checkboxes as a custom control, and it works perfect:

// Create the checkbox and add it to the DOM.
    var checkbox = $("<input type='checkbox'/>")
            .css({
                height: 20,
                width: 20,
                margin: "10px"
            })
            .appendTo($(element));

    // Determine if the change was initiated by the user.
    var changingValue = false;

    checkbox.change(function () {
        changingValue = true;
        contentItem.value = checkbox[0].checked;
        changingValue = false;
    });
    contentItem.dataBind("value", function (newValue) {
        if (!changingValue) {
            checkbox[0].checked = newValue;
        }
    });

however now I want to extend this a little, and I am wondering if anyone knows how I can count values based on whether they are true or false.

What im looking for: I have 2 checkboxes below, the 1st is "TRUE" and the 2nd is "FALSE"

  • I want to be able to count up these values using something like var count then put it in a while loop, or an array and then display it back on a button like the following for testing purposes: window.alert("add in text here" + add_code_here)

enter image description here

so example data would be:

var trueCount = 0;
var falseCount = 0;

window.alert("There are: " + trueCount + " values that are true and " + falseCount + " that are false");

and the above example trueCount = 1 and falseCount = 1

Thanks for any input people can give me, it is most appreciated


Solution

  • I couldn't get it to work with the custom control check boxes but for the standard switches this code worked for me:

    var trueCount = 0;
    var falseCount = 0;
    

    myapp.TableName.ColumnName_postRender = function (element, contentItem) { // count the true or false values contentItem.dataBind("value", function (newValue) {

        if (contentItem.value == true) {
            trueCount ++;
            falseCount--;
    
    
        } else if (contentItem.value == false) {
            falseCount++;
            trueCount--;
        }
    
    
    });
    
    //count 3 sets both trueCount and falseCount to 0 as they would already be affected by the 
    //post render method. This works by adding or subtracting the amount of false values non 
    //screen (works my my scenario)
    var count3 = 0;
    
    if (contentItem.value == false) {
        count3++;
    }
    falseCount = falseCount - count3;
    trueCount = trueCount + count3;
    

    };

    myapp.TableName.Save_execute = function (screen) {
      window.alert("True Count: " + trueCount + " | falseCount: " + falseCount);
    
     //set both count values back to 0 for when the screen is next run
     trueCount = 0;
     falseCount = 0;
    }