views:

367

answers:

2

How can I get form inputs real time and use them to change the background color of elements?

I have an input field that will accept six digit hex values:

<input name="acct-bcolor" id="acct-bcolor" class="color" value="141414">

Thanks in advance. -B

+1  A: 

This should do it:

function updateColor(){
    var len = $('#acct-bcolor').val().match(/[0-9A-F]{1}/ig).length;
    if( len == 3 || len == 6 )
        $('body').css('background-color','#'+$('#acct-bcolor').val());
}
updateColor(); // Run once at page load
$('#acct-bcolor').bind('focus',function(){
    $(this).bind('keyup', updateColor);
}).bind('blur.bgcolor',function(){
    $(this).unbind('keyup');
});

Test case

cpharmston
A: 

You can try this one:

function validateColor (color) {
   var strColor = color.toString();
   return !!strColor.match(/^([\da-f]{3}|[\da-f]{6})$/i);
}

$('#acct-bcolor').change(function () {
       var currentColor = $(this).val();
       if(validateColor(currentColor) {
          $('#colorPreview').css({'background-color' : '#'+ currentColor});
       }
    }
);
PatrikAkerstrand