Skip to main content
2 of 2
added 76 characters in body
Thomas Junk
  • 2k
  • 14
  • 18

I would do it the following way: As far as I got it, you want to select several Areas (e.g. something like Papersize and landscape or portrait format) and want to keep state of what selected so far.

I did not refactor your whole code, but reengineer it a bit:

<div id="container">    
    <div class="left unselected" id="a">A</div>
    <div class="left unselected" id="b">B</div>
</div>

For the sake of the example I limit my self to these two Areas. You could easily extrapolate to your needs.

First I bound the forEach-function from the array with the following statement:

var forEach=Function.prototype.call.bind([].forEach);

After that I used an object to keep the state for me:

var selectedItems={
    a:false,
    b:false,
    c:false,
    d:false
};

That's what you usually would do with something like a "Model"

(cf. Backbone.Model.extend({}); in http://backbonejs.org/).

But for this usecase, that simple object would do the trick.

Next I would define a toggle function for each group (in my example only for "left"):

var toggleSelectionLeft=function(elem){
    target=$(elem.target);
    target.hasClass("selected")?target.removeClass("selected"):target.addClass("selected"); 
    var id=elem.target.id;
    selectedItems[id]=!selectedItems[id];
};

This togglefunction handles the adaption of the css and sets the state of our object. Usually you would further decouple these tasks, in only triggering an "elementSelected" event, to which thwo functions would subcribe: (1) update the model and (2) adapt the CSS. These are two different tasks. For the sake of this simple example I left them together (So don't do this at home g).

After all your behaviour is declared, you could go on, binding the "click" to the wanted behaviour:

forEach($(".left"), function(elem){
    $(elem).on("click", toggleSelectionLeft);
});

A working example is under: http://jsfiddle.net/Susv4/ For submitting values to the server you could easily evaluate our "model".

Thomas Junk
  • 2k
  • 14
  • 18