简体   繁体   中英

Change background-color with input value

I have a form in which user can set a hexa color. I want to put a block next to the input "color" and that this block change background color according to the input value. I want to make this dynamically, a bit like a color picker. I think we can do this with js but I don't know how. Also I do this with rails if it can help.

I already have this

<div class="field color">
    <label for="activite_color">Color</label>
    <input type="text" value="BF4139" name="activite[color]" id="activite_color" />
    <span class="col-lg-1" style="background:#BF4139;"></span>
</div>

And the fiddle

Add maxlength="6" to textbox :

HTML:

<input type="text" value="BF4139" name="activite[color]" id="activite_color" maxlength="6" />

JavaScript:

$('#activite_color').on('keyup', function() {
    $('.col-lg-1').css('background', '#' + $(this).val());
});

Demo: https://jsfiddle.net/tusharj/rt7h6wd3/1/

I've got on input

$('#activite_color').on('input', function() {
    $('.col-lg-1').css('background', '#' + $(this).val());
});

any of the answers so far will work though

https://jsfiddle.net/rt7h6wd3/3/

$(function () {
    $('#activite_color').change(function () {
        $('.col-lg-1').css('background', '#' + $(this).val());
    });
});

Check the update on your jsfidder which i have made.

You can do this.

Html: <input type="text">

Script
$("input").blur(function(){
   var col = "#" + $("input").val();
   $("body").css("background-color", col);
});

remember color code is 6 digit. so enter 6 digit in text box.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM