javascriptjscolor

Added row to table with jscolor colour picker but picker not showing


I am using a jscolor picker in a table. This works in a row that is in the original HTML. However when I add a row from javascript the colour picker does not work. When inspecting the HTML created the input tag is identical. I think there must be something about the registering of this element with the jscolor js.

here is minimal HTML to demonstrate the problem:

        <head>
            <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.min.js"></script>
        </head>
        <button onclick="add_row_to_table()">Add Row</button>
        <table>
            <thead>
            <tr><th>Colour</th></tr>
            </thead>
            <tbody id="tableBody">
            <tr><td><input class="jscolor"></td></tr>
            </tbody>
        </table>

        <script type="text/javascript">
            function add_row_to_table(p) {
                tableBody = document.getElementById('tableBody');
                newRow = document.createElement('tr');
                colourCell = document.createElement('td');
                colourWidget = document.createElement('input');
                colourWidget.setAttribute('class', 'jscolor');
                colourWidget.setAttribute('autocomplete', 'off');
                colourWidget.setAttribute('style', 'background-image: none, background-color: rgb(255, 255, 255); color: rgb(0, 0, 0);');
                colourCell.appendChild(colourWidget);
                newRow.appendChild(colourCell);
                tableBody.appendChild(newRow);
            }
        </script>


Solution

  • there is a problem with the <script type=... and you need to register the new input with new jscolor(... here is a working code

    <html>
      <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.min.js"></script>
      </head>
      <body>
        <button onclick="add_row_to_table()">Add Row</button>
        <table>
          <thead>
            <tr><th>Colour</th></tr>
          </thead>
          <tbody id="tableBody">
            <tr><td><input class="jscolor"></td></tr>
          </tbody>
        </table>
        <script type="text/javascript">
          function add_row_to_table(p) {
            tableBody = document.getElementById('tableBody');
            newRow = document.createElement('tr');
            colourCell = document.createElement('td');
            colourWidget = document.createElement('input');
            colourWidget.setAttribute('class', 'jscolor');
            colourCell.appendChild(colourWidget);
            newRow.appendChild(colourCell);
            tableBody.appendChild(newRow);
            new jscolor(colourWidget);
          }
        </script>
      </body>
    </html>
    

    https://jsbin.com/jaxixod/edit?html,output