How do you make just some text, inside an input text field, bold?

clinchergt picture clinchergt · May 31, 2012 · Viewed 25.6k times · Source

I'm trying to get bold specific text, inside an input text field. I'm not sure how to go about it since html code isn't interpreted inside a text field, so anything like <b> won't work. Is it possible to bold just some text? Methods like bold() only add <b> around the string.

Thanks

Answer

Mic picture Mic · May 31, 2012

Here is one trick.

An INPUT field is over a SPAN. With a an example of function that puts the 3 first chars in bold. You may run into transparency trouble with older browser. In that case you can leave the normal input field without the bold effect.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>transp</title>
    <style>
        div{
            position:relative;
        }
        input, span{
            top:0;
            position:absolute;
            width:120px;
        }
        span{
            top:2px;
            left:2px;
            z-index:1;
            overflow:hidden;
        }
        input{
            background:transparent;
            z-index:2;
        }
    </style>
</head>
<body>
<div>
    <input onkeyup="bold3(this)" />
    <span id="back"></span>
</div>
<script>
function bold3(inp){
    inp.style.color = 'transparent';
    var span = document.getElementById('back');
    span.innerHTML = 
        '<b>' + 
        inp.value.substr(0, 3) + 
        '</b>' + 
        inp.value.substr(3);
}
</script>
</body>
</html>