vendredi 4 août 2017

How do I generate all combination of values from selected checkboxes in Javascript?

I have a string object with values:

I have a page with checkboxes of 4 categories (1-4), e.g. checkboxes "a1","b1","c1", "d1", "a2", "b2", "c2", "d2", "a3","b3","c3","d3", "a4","b4","c4","d4".

When the user selects random variables, I need to generate and display all combinations of selected variables, with a requirement of having at least one variable from group 1, at least one from group 2, etc.

For example, if the user selected "a1", "b2", I need it to show:

a1+b2+c3+d4
a1+b2+c4+d3

index.html:

      <p><div id="displaySelectedVarsCombos">
      </div></p>


<table>
            <tr>
              <td><label><input type="checkbox" name="selected" value="a1" class="offers" />a1</label></td>
              <td><label><input type="checkbox" name="selected" value="a2" class="offers" />a2</label></td>
              <td><label><input type="checkbox" name="selected" value="a3" class=".offers" />a3</label></td>
              <td><label><input type="checkbox" name="selected" value="a4" class="offers" />a4</label></td>
              </tr>
            <tr>
              <td><label><input type="checkbox" name="selected" value="b1" class="offers" />b1</label></td>
              <td><label><input type="checkbox" name="selected" value="b2" class="offers" />b2</label></td>
              <td><label><input type="checkbox" name="selected" value="b3" class="offers" />b3</label></td>
              <td><label><input type="checkbox" name="selected" value="b4" class="offers" />b4</label></td>
              </tr>
      ...
             </table>
        <script src="/static/my_jq.js" type="text/javascript"></script>

my_js:

$(function(){
$(".offers").on("click", function(){
  var arr = $(".offers:checked").map(function(){
  return $(this).val();
    }).get();
  $('#displaySelectedVarsCombos').html(arr.join('+'));  
})
})

This one only shows the selected variables as a string. How do I make it show all combinations of selected variables?




Aucun commentaire:

Enregistrer un commentaire