lauren / pick-a-color

an easy-to-use jQuery color picker for Twitter Bootstrap
http://lauren.github.com/pick-a-color/
MIT License
269 stars 89 forks source link

Enhancement: Allow programmatic changing of color #94

Open isi-dwade opened 4 years ago

isi-dwade commented 4 years ago

On my site, I needed to be able to change the value of the control programmatically. So I introduced two enhancements:

at the top of the latest 1.2.3 build, after the 'use strict' statement, I added this statement:

    $.fn.setColor = function (value) {      
        return $(this).find('input').val(value).trigger('changeInput');
    }

In the Initialize funciton, I added this statement:

          $thisEl.on('changeInput', function(e) { methods.updatePreview($thisEl) });
OllisGit commented 4 years ago

Thx a lot @isi-dwade !!!

I needed to remove the find-input, then it was working for me:

    $.fn.setColor = function (value) {
        return $(this).val(value).trigger('change');
    }
isi-dwade commented 4 years ago

@OllisGit Glad it helped you. In my case, I needed the find('input') because this is the DIV of the control, not the actual input control that holds the value. Maybe it depends on when you use the function (before or after initializing the control). After the control is initialized, it wraps the input in a DIV with the same ID as the input.

<div class="input-group pick-a-color-markup" id="nameColor">
<input type="hidden" name="nameColor" id="nameColor" class="pick-a-color form-control" value="576d7b">
.....
</div>

By the way, you can also override the basic color list with your own (see below).

My initialization code preceeds my calling setColor.

$(".pick-a-color").pickAColor({
    showSpectrum: false,
    showAdvanced: false,
    showSavedColors: false, 
    showHexInput: false,
    basicColors: {      
        Default: 'fff',
        'Color1':'de5b35',   
        'Color2': '576d6b',   
    },
});

$("#nameColor").setColor('576d6b');