Domanda

Can we display part of a text box to be read-only with default value?

I want to display a number preceded by two Zero's in a text box and the two zeros must not be editable.

È stato utile?

Soluzione

It is not possible to make a textbox part readonly (at least with pure css and html) and part not. However you could do something similar to how twitter bootstrap does it, just change the background color to white to make it appear to be one input.

HTML:

  <div class="input-group">
    <input type="text" class="form-control">
    <span class="input-group-addon">.00</span>
  </div>

Override:

.input-group { 
    width:50%;
}
.input-group .form-control {
    border-right:none;
}
.input-group .input-group-addon {
    background-color:#fff;
    border-left:none;
}

Fiddle:

http://jsfiddle.net/QJu3y/2/

Bootstrap:

http://getbootstrap.com/components/#input-groups-basic

Altri suggerimenti

You could do it like this. Just check that the two zeros are at the beginning of the value each time the value is changed, and if not, add them back in.

Javascript:

function zOnChange()
{
    var ele = document.getElementById('zeronumber');
    var value = ele.value;
    if( value.substring(0,2)!='00' )
    {
        if( value.substring(0,1)=='0')
        {
            ele.value = '0' + value;
        }
        else
        {
            ele.value = '00' + value;
        }
    }
}

Html:

<input type='text' id='zeronumber' value='00' onChange='zOnChange()' onKeyUp='zOnChange()' />

I like this because unlike the other solutions, you can select the whole text box and delete it (but the 00 comes back). And it doesn't break the End button like the pretty cool solution you've got at jsfiddle.net/Yt72H.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top