Search code examples
jqueryhtmlcsscolor-picker

Color picker not adding to dynamic HTML table


Im trying to add a color picker to a HTML but its not working.

fiddle:

https://jsfiddle.net/csgn6051/2/

Here is my code:

HTML

<button id="add">
  Add to table
</button>
</button>
<table id="points-table" border="1">
  <tr>
    <td>line-item</td>
    <td>color-picker</td>
  </tr>
</table>

Jquery:-

$(document).ready(function() {

$('#add').click(function() {
    alert('clicked')
    $('#points-table tr:last').after('<tr>' + '<td>1</td>'

      + '<td>   <input class="jscolor" value="ab2567"/>    </td></tr>');

  })


})

Solution

  • You need to get the color value using .val() and assign it to a variable. Then use the variable fir the input value in the table.

    See fiddle https://jsfiddle.net/csgn6051/5/

    $(document).ready(function() {
    $('#add').click(function() {
        var color = $('#color').val();
        $('#points-table tr:last').after('<tr>' + '<td>1</td>'
          + '<td>   <input class="jscolor" value="'+color+'"/>    </td></tr>');
    
       //This part below came from the comment by A. Wolf
       new jscolor($('#points-table tr:last').find('.jscolor')[0])
      })
    })