1

I create a n*n table by a for loop, then I change the value of n and want to reload table to show the new table.

 <table id = "chessboard">
       <script>
            createChessboard()
       </script>
 </table>

javaScript:

function createChessboard() {
        document.write('<tr><td></td>')
        for (var column=0;column<size;column++){
            document.write("<td>"+(column+1)+"</td>")
        }
        document.write('</tr>')
        for(var row=0;row<size;row++){
            document.write("<tr>")
            document.write("<td>"+(row+1)+"</td>")
            for(var column=0;column<size;column++){
                if(column%2 == row%2){
                    document.write("<td><input id="+row+column+" type=button onclick='putQueen(id)' style='background:#E5E4E2'/>")
                }else {
                    document.write("<td><input id="+row+column+" type=button onclick='putQueen(id)' style='background:gray'/>")
                }

            }
            document.write("</tr>")
        }
    }

how to do it in a onchange() method?

Ruochen Liu
  • 13
  • 1
  • 3
  • 1
    How do you change the value of n? – Mouneer Mar 04 '17 at 16:11
  • the var size(n) is controlled by a select, so I try to do it in select's onchange() – Ruochen Liu Mar 04 '17 at 17:05
  • please remember to accept [@Mouneer's answer](https://stackoverflow.com/a/42599562/4770813) if [you believe is the correct one](https://stackoverflow.com/questions/42598117/how-to-reload-a-table-which-is-created-by-javascript#comment72347277_42599562) for your question, it encourages the *answerer* to keep on helping and informs the community your question has been successfully resolved, [more on why is marking the correct answer important](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – Scaramouche Mar 31 '19 at 00:56

2 Answers2

0

You can’t use document.write() in an onchange method (in fact, in any callback method). It’s a pretty old-fashioned method that is very rarely used in modern JavaScript.

Instead, you can assing id="..." to the elements you want to change (make sure they are unique), and then you would be able to use innerHTML to change their values, like this:

var board = document.getElementById('chessboard');
board.innerHTML = '<strong>Test</strong>';

This code would replace your table with a bold 'Test' text. You could add IDs to single colmns in the table, and then access them this way.

In fact, this is also a recommended way to generate your board. Unlike document.write, it doesn’t require you to put <script> tag inside <table id="chessboard">, allowing for separation of code and presentation. Just make sure that <table id="chessboard"> already exists by the time your code is run (the easiest way to ensure this is to place your <script> tag below your table, in the end of the document).

Or, if you use the jQuery library, as the tags to this question assume (but perhaps you don’t use it), you could use this code:

var $board = $('#chessboard');
$board.html('<strong>Test</strong>');

It’s equivalent to the code above and uses innerHTML under-the-hood, but it’s a bit shorter. If you don’t know jQuery, you perhaps don’t need it, you can do the same in vanilla JavaScript.

If you don’t want to assign IDs to all the elements, you could use

var board = document.getElementById('chessboard');
var trs = board.getElementsByTagName('TR');

to get a list of TRs in your table, and then iterate over table rows as over an array. When you find the table row you want, you can use something like trs[0].getElementsByTagName('TD') to get the list of table cells within this row. But this seems less convenient than using IDs.

As an option to innerHTML, you can use direct DOM manipulation functions. When a browser reads HTML, it converts it into another form, DOM. DOM represents same things as HTML, but it’s not a string, it’s a structured representation.

JavaScript can either use innerHTML to change DOM objects, or use functions to manipulate DOM directly. But’s often more convenient than changing the HTML code directly, because the browser has done the parsing for you.

Please see the Introduction to the DOM by Mozilla for an explanation.

  • you are right, but I have to use for loop to create the table, because the size of the chessboard is not fixed. when I change the value of size, how to make the table run this for loop again? – Ruochen Liu Mar 04 '17 at 17:12
  • or other way to implement a chessboard with dynamic size by a select box? – Ruochen Liu Mar 04 '17 at 17:13
  • Change your code so that it doesn't use document.write, and adds content to string instead: add var html = ''; in the top of your function, and replace all the instances of document.write('') with html += ''; — then, do document.getElementById('chessboard').innerHTML = html; in the end of the function. Then, add some id to your select box (like – Dzmitry Kushnarou Mar 04 '17 at 17:18
  • Sorry, I meant document.getElementById('size-select').addEventListener('cha‌​‌​nge', function () { size = this.options[this.selectedIndex].text; /* Call your func here */ }, false); You don't need var because you're modifying an outside variable 'size'. – Dzmitry Kushnarou Mar 04 '17 at 17:22
0

I just replaced document.write because it's a bad practice. So, every time you change the select the table DOM element is being drawn.

function createChessboard(size) {
  var innerHTML = '<tr><td></td>';
  for (var column=0;column<size;column++){
    innerHTML += "<td>"+(column+1)+"</td>";
  }

  innerHTML += '</tr>';
  for(var row=0;row<size;row++){
    innerHTML += "<tr>";
    innerHTML += "<td>"+(row+1)+"</td>";
    for(var column=0;column<size;column++){
      if(column%2 == row%2){
        innerHTML += "<td><input id="+row+column+" type=button onclick='putQueen(id)' style='background:#E5E4E2'/>";
      } else {
        innerHTML += "<td><input id="+row+column+" type=button onclick='putQueen(id)' style='background:gray'/>";
      }          
    }

    innerHTML += "</tr>";
  }

  var chessEl = document.querySelector('#chessboard');
  chessEl.innerHTML = innerHTML;
};

createChessboard(5);

function changeSize(el) {
  var val = el.options[el.selectedIndex].value;
  createChessboard(val);
}
  <form>
    <select onchange="changeSize(this)" >
      <option value="5"> 5 </option>
      <option value="8"> 8 </option>
    </select>
  </form>

  <table id ="chessboard">
  </table>
Community
  • 1
  • 1
Mouneer
  • 12,827
  • 2
  • 35
  • 45