vendredi 22 juillet 2016

Get all checked checkboxes, possibly with same value

I have prepared a jsFiddle for my question:

screenshot

In a word game I would like to display a dialog with all letter tiles in player's hand - and allow her to select some for swapping with the pile.

The letters are not unique, for example a player might have a hand "ABCDAB" as in the above screenshot - and select "ABA" for swapping.

Here is my code -

HTML (with dialog and button):

<div id="swapDlg" title="Swap letters">
  <p>Select letters for swapping:</p>
  <div id="swapList">
  </div>
</div>

<button id="swapBtn">Swap letters</button>

JavaScript:

$(function() {
  $('#swapDlg').dialog({
    modal: true,
    minWidth: 400,
    autoOpen: false,
    buttons: {
      'Swap': function() {
        $(this).dialog('close');
        var result = 'How to get all selected letters?' // HERE
        alert('You would like to swap: ' + result);
      },
      'Cancel': function() {
        $(this).dialog('close');
      }
    }
  });

  $('#swapBtn').button().click(function(e) {
    e.preventDefault();
    $('#swapDlg').dialog('open');
  });

  var str = 'AB*CD*AB';
  var checkBoxes = [];
  for (var i = 0; i < str.length; i++) {
    var letter = str[i];
    if (letter != '*') {
      checkBoxes.push('<label><input type="checkbox" value="' +
        letter + '">&nbsp;' + letter + '</label>');
    }
  }

  $('#swapList')
    .empty()
    .append(checkBoxes.join('<br>'));
});

Please help me with the line marked by the // HERE comment.

How to get there the result as a string with all checked values?




Aucun commentaire:

Enregistrer un commentaire