using jscolor.js on dynamic input

前端 未结 4 1446
说谎
说谎 2021-01-04 16:23

i\'m using color picker from http://jscolor.com/

i\'m trying to attach it to some dynamic inputs, but to no avail. dynamic inputs in terms of, on page load the input

相关标签:
4条回答
  • 2021-01-04 16:48

    For some reason jscolor.init() did not work for me, and looking at the code I called

    jscolor.installByClassName("jscolor");

    function.

    So...

    $(document).ready(function() {
      jscolor.installByClassName("jscolor");
    });
    

    Hope it helps

    0 讨论(0)
  • 2021-01-04 16:48

    This helped me

    <script>
     $(document).on('click', '#myPickerId', function () {
        var obj = $(this)[0];
        if (!obj.hasPicker) {
            var picker = new jscolor.color(obj, {});  //
            obj.hasPicker = true;
            picker.showPicker();
        }
    });    
    </script>
    

    In my case, the picker control was dynamic because it is inside Knockout.js 'with' statement which hides and recreates the picker when it needs.

    0 讨论(0)
  • 2021-01-04 17:00

    As of 2020, the original problem should be solvable by dynamically creating an input element, and then calling new jscolor(input). Using JQuery (you could use vanilla JS as well):

    var color_input = $('<input class="jscolor" spellcheck="false">');
    new jscolor(color_input[0]);
    

    This will make the popup picker appear on click, and everything appears to work just fine. However, you cannot manipulate it programmatically. To set the color using the objects above, you would normally use a method like: color_input[0].jscolor.fromString("#B7B7B7"). But that will fail for dynamically created objects, as color_input[0].jscolor is undefined. I believe this is a bug in Jscolor (and probably very easily solvable), as the missing object is actually available with color_input[0]._jscLinkedInstance. So you can just set the object yourself on instantiation with:

    var color_input = $('<input class="jscolor" spellcheck="false">');
    color_input[0].jscolor = new jscolor(color_input[0]);
    

    And then everything looks to be working as expected. Hopefully this helps someone else that comes across this answer page as I did.

    0 讨论(0)
  • 2021-01-04 17:08

    I just had this problem too but luckily it's easy to fix. You need to (re)init jscolor after you have dynamically created your inputs:

    jscolor.init()
    
    0 讨论(0)
提交回复
热议问题