Search code examples
jquerybit-manipulationbitflags

jQuery bitwise element selection


Perhaps I'm think about this the wrong way, but I'm trying to fade out some html elements on my page depending on the flags selected via check-boxes on the same page.

I have many <div class"bar"> on the page.

Each of these bar divs will have an "issueflag" - <div class"bar" data-issueflag="3">

The value of "issueflag" will be a bitwise value of...

1 - Barcode Issues 2 - Missing Data 4 - Notes Submitted ...add so on.

So, for example, if the "issueflag" value is 3, the bar has "Barcode Issues", and "Missing Data".

My page will have check-boxes each have a value the flags.

When the state of the check-boxes are modified, I'd like the elements that do not match the selection to fade out, an those that do fade in.

Hopefully this will help understand what I'm after...

http://jsfiddle.net/ETFairfax/Bj4Vb/

My question is how do I do bitwise selection in jQuery?

Any help appreciated.

Markup

<h3>Make your selection</h3>

<input type="checkbox" id="checkboxBarcode" value="1" />Barcode Issue (1)
<br/>
<input type="checkbox" id="checkboxInputMissing" value="2" />Missing Input (2)
<br/>
<input type="checkbox" id="checkboxNotesSubmitted" value="4" />notes Submitted (4)
<br/>

<h3>Results</h3>

<div id="container">
    <div class="bar issueflags1" data-issueflag="1">1</div>
    <div class="bar issueflags2" data-issueflag="2">2</div>
    <div class="bar issueflags4" data-issueflag="4">4</div>
    <div class="bar issueflags7" data-issueflag="7">7</div>
</div>

JavaScript/jQuery

$("input:checkbox").click(function () {

    var selectionSum = 0;

    $("input:checkbox:checked").each(function () {
        selectionSum += parseInt($(this).val(), 10);
    });

    var $bars = $("#container .bar");

    $bars.fadeTo("fast", 1, function () {

        if (selectionSum != 0) {

            // This is wrong, but shows how I would like the UI to sort of behave (some fine tuning needed!)...
            $bars.not(".issueflags" + selectionSum).fadeTo("slow", 0.5);

            // I need something along the lines of a c#/linq query like:
            // $("#container .bar").where(b => b.issueflag & selectionSum == 0).fadeTo("slow", 0.5);
        }
    });
});

CSS

#container {
    width: 300px;
    height: 300px;
}
.bar {
    margin-top: 10px;
    background-color: YellowGreen;
}

Solution

  • Try this:

    $bars.filter(function() {
       return (parseInt($(this).attr('data-issueflag')) & selectionSum) === 0;
    }).fadeTo("slow", 0.5);
    

    http://jsfiddle.net/Bj4Vb/1/