Search code examples
jqueryjscolor

jscolor.js change on dynamic input


Situation

I am using the jscolor color picker for my project. I load the input field colors using an ajax call. When i have inserted the value to the input field i fire document.getElementById('ktxt').jscolor.importColor(); to update the color picker value.

Issue

I have updated to the latest jscolor.js version (2.3.3, release date 11/08/2020).

After this update i had to change a few things, the new version uses data-jscolor="" instead of the class jscolor. I made all necessary changes, but i am not able to get the jscolor box updated after dynamically loading my input field values.

I have qouted out the things i tried already in the example below. I also cannot find an answer in there documentation

function loadColor() {
  $("#ktxt").val('FF1212');
  $("#kbg").val('26FF35');
  jscolor.trigger('input change')
  //document.getElementById('ktxt').jscolor.trigger('input change');
  //document.getElementById('ktxt').jscolor.fromString('26FF35')
  //document.getElementById('ktxt').jscolor.importColor();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.3.3/jscolor.min.js"></script>

<button onclick="loadColor()">Load Preset Colors</button>

<input type="text" id="ktxt" data-jscolor="" class="form-control" name="ctxt" value="">
<input type="text" id="kbg" data-jscolor="" class="form-control" name="cbg" value="">


Solution

  • From the document you can use fromString as below. You will need picker object so use $('#ktxt')[0].jscolor.

    Try it beow.

    function loadColor() {
      $('#ktxt')[0].jscolor.fromString('#FF1212');
      $('#kbg')[0].jscolor.fromString('#26FF35');
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.3.3/jscolor.min.js"></script>
    
    <button onclick="loadColor()">Load Preset Colors</button>
    
    <input type="text" id="ktxt" data-jscolor="" class="form-control" name="ctxt" value="">
    <input type="text" id="kbg" data-jscolor="" class="form-control" name="cbg" value="">