I’m trying to create a colour picker based on colours specified in a dropdown box with the code below (jsfiddle here)
HTML:
<select id="colour" name="colour">
<option value="000000">Black</option>
<option value="CCCCCC">Grey</option>
<option value="EAEAEA">Light Grey</option>
</select>
JS:
$(function() {
var $colourcontainer = '<div id="colour-palette"></div>';
$( '#colour' ).after( $colourcontainer );
$( '#colour option' ).each( function() {
$val = $(this).val();
if( $val ) {
$( '#colour-palette' ).append( '<div class="colour" style="background-color:#'+$val+';"></div>' ).click( function() {
$('#colour:last').val($val);
alert($val);
});
}
});
});
The problem I’m having is getting it to loop just once for each dropdown option as right now it loops several times and adds multiple onclicks to each colour.
It adds multiple clicks because you are binding a click handler to the
#colour-palettein each iteration (here 3 iterations).A better approach would be to create the
.colourelement add the color as a data property and then use the on click handler to assign the click event of#colour-paletteto.colorelement to theTry this:
Working JSFiddle: http://jsfiddle.net/Rf9L3/1/