1

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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});
       }
    }
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.