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.