How can I add an unremovable prefix to an HTML input field?

Using jQuery, how can I add a default value of http:// into an input field that can’t be removed, but that still allows you to type a URL after it?

Default: http://
Url: http://www.domain.name


this works well for me:

$("input").keydown(function(e) {
var oldvalue=$(this).val();
var field=this;
setTimeout(function () {
    if(field.value.indexOf('http://') !== 0) {
        $(field).val(oldvalue);
    } 
}, 1);
});

http://jsfiddle.net/J2BKU/


I had the same problem and solved it without using jquery, just simple CSS and HTML. The solution looks elegant and the user will immediately understand how it works.

Use the following code in your html:

span.textbox {
	    background-color: #FFF;
	    color: #888;
	    line-height:20px;
	    height:20px;
	    padding:3px;
	    border:1px #888 solid;
	    font-size:9pt;
}
    
span.textbox input {
      border: 0px;
	    background-color: #FFF;
  }
 (short title): 
    <span class="textbox"> 
        http://
        <input type="text" name="url" autofocus />
    </span>

    

The result will look like this (copied the result from my script, so it doesn't say http://):

enter image description here

Note that you only have to prepend the http:// in your script, but that will make it work perfectly.


That's not possible. You can put a value in the input field, but it can be deleted.

You can put the text outside the input field, that will protect it from being deleted, but it won't be included in the value when the form is posted.

You can use absolute positioning to put the input field on top of the text, and use padding in the field so that you start typing after the text. Example:

CSS:

.UrlInput { position: relative; }
.UrlInput label { position: absolute; left: 3px; top: 3px; color: #999; }
.UrlInput input { position: absolute; left: 0; top: 0; padding-left:40px; }

HTML:

<div class="UrlInput">
  <label>http://</label>
  <input name="Url" type="text" />
</div>