Alex Rivera | Logout

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

Asked 2010-12-27T00:06:42.287
58

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

Edit
Report

1 Answer

0

I'm not sure about jQuery, but in plain JS, you can try to detect when the field changes and if the change somehow ruined the prefix, add it back (not 100% foolproof - if you want that, you have to just put the "http://" in a span outside the input field and add later programmatically):

<script>
function checkHttp(input) {
    // See if someone deleted 1 character from needed prefix.
    // We can't simply check if the string starts with the prefix
    // since the user may have backspaced out 1 character.
    input.value = input.value.replace(/^http:\/\//, "");
    input.value = input.value.replace(/^http:\//, "");            
    input.value = input.value.replace(/^http\/\//, "");            
    input.value = input.value.replace(/^htt:\/\//, "");            
    input.value = input.value.replace(/^htp:\/\//, "");            
    input.value = input.value.replace(/^ttp:\/\//, "");
    // This doesn't work if someone deletes - say via cut - >1 character.
    input.value = input.value.replace(/^/, "http://");
}
</script>
<input type='text' name='x' id='x' value='http://' onChange='checkHttp(this)'>

Please note that such a weird behavior is really confusing to the user without either explicit explanation beforehand, OR a pop-up (may be non-modal one) explaining that you fixed his mistake for him.

answered 2010-12-27T00:19:32.587

Your Answer