vendredi 25 août 2017

Trouble with changing checkbox states on jQuery

I'm developing a game to test some properties of control codes. The based-game is this well-known magic one: you have some cards with numbers and select all cards which a number of your choice appears. Then, the "magician" can discover your number using binary code of cards you have selected. A very simple version is as follows:

card 1 (represents bit xx1 if selected)

  • 1
  • 3
  • 5
  • 7

card 2 (bit x1x)

  • 2
  • 3
  • 6
  • 7

card 3 (bit 1xx)

  • 4
  • 5
  • 6
  • 7

In example, if you are thinking on number 3, you'll select cards 1 and 2, that represents (011) in binary, that's number 3.

Well, this explanation is to put you in context. My version of the game have additionally a layer of verification cards and numbers. You can find the actual code in this codepen. It's full of alerts to give me info about variables. If you run it you'll find first execution is ok, but next tries it starts to being crazy.

I have some troubles with check/uncheck checkboxes with jQuery. I've tried many solutions and read documentation and other related posts, but nothing appears to solve this issue. I think there's some troubles with the scope of the $lie var. When I click button, it's supossed to $lie = ''; and after another function $lie gets a new value. This is correct, but when I pass $lie to this function it remembers previous value.

I'm copying here the complete skeleton of the functions that works with or are related to $lie var:

var $lie = '';
function check() {
    $lie = ''; // only to clear on successive calls
    if (something) {
        // $lie gets its correct value here
    }
    return $lie; //I have made some alerts here and it is working well always
}

function lying() {
    if ($lie === something) {
         // something related with "something"
    }
}

function message($lie) {
    // other stuff
    $(some-div).on('click', function() {
        // more stuff
        $change = $('#' + $lie); // here $lie gets the first value, but not reset on successive tries, that is why program goes crazy
        $change.prop('checked', function(i, i2) {
            return !i2;
        });
    });
}

$(run-button).on('click', function(e) {
    e.preventDefault();
    check();
    if ($lie !== '') { // do only if $lie have value
        lying();
        message($lie)
    }
}

First time I execute the program $lie have a correct value and works properly. But next runs the $lie value is not reset and remember the previous value. I'm not sure where is the mistake, I've tried to reset $lie = ''; in many places, but ever is handling the first value to the message($lie); function.

Thanks for your help and your suggestions and excuse me if the answer is in other post and I've not seen it!




Aucun commentaire:

Enregistrer un commentaire