Problem with JoubelUI.createButton

papi Jo's picture

Hi there,

In the process of developing new features for the Dialog Cards library I am confronted with the following problem.

<code> C.prototype.createNumberCards = function () {
    var self = this;
    var $numberCards = $('<div>', {
      'class': 'h5p-dialogcards-number',
      'html': "How many cards do you want? "
    });
    var $nbCards = 20;
    for (i = 5; i <$nbCards; i+= 5) {
      switch (i) {
      case 5:
        self.$Button = JoubelUI.createButton({
          'html': i
        }).click(function () {
          alert(i);
        }).appendTo($numberCards);
        break;
      case 10:
        self.$Button = JoubelUI.createButton({
          'html': i
        }).click(function () {
          alert(i);
        }).appendTo($numberCards);
        break;
      };
    };
    return $numberCards;
  };</code>

This is not a fully-working example, but is enough to explain my problem.

The buttons are correctly created. But when I click on either button "5" or button "10" I get a value of "20" when I am expecting to get respective values of 5 and 10. Why is that?

tim's picture

Hi, 

it could be to do with the way javascript executes the alert function. My guess is that alert is only called when the for loop has run to completion, thus printing 20. You could check if this is the case by setting $nbCards = 15. 

I would try saving 'i' as a variable in each 'case' in your switch statement and alerting with that. 

papi Jo's picture

Thanks for your reply, tim. It did not give a solution but helped me pursue my quest. This is it, inside a loop.

<code>
$nbAllCards = 20;
for (var i = 5; i < $nbAllCards; i+= 5) {
  self.$Button = JoubelUI.createButton({
      'class': 'h5p-dialogcards-number-button',
      'title': i,
      'html': i,
      'id': i
    }).click(function () {
        alert(this.id);
    }).appendTo($numberCards);
};
</code>

Of course I could also have used this.title or this.html as values, but I prefer to attach an 'id' parameter to the buttons.

By the way, why is the <code> tag not working on this forum?

tim's picture

That's excellent that you got it working! Yes, the forum's a bit outdated but that's what we've got for now :)