title: Select random table cells with js
body: <p>First I have a form, with 2 fileds <code>board</code> field and <code>myNumb</code>, the board is the number that controls the table size. <code>myNumb</code> is the number of cells that should be selected randomly.</p>
  
  <p>I am trying to select random table cells with javascript. I have a integer variable <code>myNumb</code> where I will give how many random cells should be selected. In the selected cells I want to put 1 and the rest of them 0. I have built the structure of the table, but don't have a idea how to select random cells. Any ideas would be much appreciated.</p>
  
  <pre><code>function tableMatrix () {
      //taking values from the form
      var board = document.forms["myForm"]["board"].value;;
      var myNumb = document.forms["myForm"]["myNumb"].value;
      var zero = 0;
      var one = 1;
  
      //finding myContainer
      var myContainer = document.getElementById('myContainer');
      myContainer.innerHTML = '';
      //creating element &lt;table&gt;
      var table = document.createElement('table');
  
      table.style.width = '100%';
      table.setAttribute('border', '1');
  
      //creating element &lt;tbody&gt;
      var tbody = document.createElement('tbody');
  
      //cells creation
      for (var i = 0; i &lt; board; i++) {
          //creating &lt;tr&gt; element
          var tr = document.createElement('tr');
          for (var j = 0; j &lt; board; j++) {
              //creating &lt;td&gt; element
              var td = document.createElement('td');
              //put &lt;td&gt; after &lt;tr&gt; element
              tr.appendChild(td);
              td.setAttribute('class', 'tblCells');
  
              var x = 0;
              if (x &lt;= myNumb) {
                  var randomCounter = Math.floor(Math.random() * 9);
                  x += randomCounter;
                  td.innerHTML = '&lt;span&gt;'+ one +'&lt;/span&gt;';
              } else {
                  td.innerHTML = '&lt;span&gt;'+ zero +'&lt;/span&gt;';
              }
          }
          //put &lt;tr&gt; after &lt;tbody&gt; element
          tbody.appendChild(tr);
      }
      //put &lt;tbody&gt; after &lt;table&gt; element
      table.appendChild(tbody);
      //put &lt;table&gt; after &lt;div&gt; element
      myContainer.appendChild(table);
  
  }
  </code></pre>
  
  <p>I have created also a JSFiddle <a href="https://jsfiddle.net/9ot5ryf3/1/" rel="nofollow">here</a> if it helps</p>