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

JqueryHtml

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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/

Solution 2 - Jquery

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.

Solution 3 - Jquery

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>

Solution 4 - Jquery

Check this format util and a prefix implementation for it:

  • no glitching
  • flexibility with regex
  • any input event (keyboard, mouse, drag-n-drop, etc.)
  • universal utility (extra formatters can be added)
  • bug tested

// Util function
function addFormatter (input, formatFn) {
  let oldValue = input.value;
  
  const handleInput = event => {
    const result = formatFn(input.value, oldValue, event);
    if (typeof result === 'string') {
      input.value = result;
    }
    
    oldValue = input.value;
  }

  handleInput();
  input.addEventListener("input", handleInput);
}

// Example implementation
// HOF returning regex prefix formatter
function regexPrefix (regex, prefix) {
  return (newValue, oldValue) => regex.test(newValue) ? newValue : (newValue ? oldValue : prefix);
}

// Apply formatter
const input = document.getElementById('link');
addFormatter(input, regexPrefix(/^https?:\/\//, 'http://'));

input { padding: 0.5rem; font-size: 1rem; }

<input type="text" id="link" />

Solution 5 - Jquery

I’ve seen some web forms include this value outside of the field, e.g.

<label for="url">URL:</label> http:// <input id="url" type="text">

But if you’re dead set on enforcing the value via JavaScript (and bear in mind that users can turn JavaScript off), you could write a function that fires every time the user types in the field, and adds http:// to the start of the field if it’s not there. E.g.

HTML:
<label for="url">URL:</label> <input id="url" type="text" value="http://">

### JavaScript:

$('#url').keyup(function(){

    if( this.value.indexOf('http://') !== 0 ){ 
        // Add lots more code here so that this actually works in practice.    
        // E.g. if the user deletes only some of the “http://”, if the 
        // user types something before the “http://”, etc...
        this.value = 'http://' + this.value;
    }
});

Solution 6 - Jquery

Here is a HTML and CSS only option that, in my opinion, is cleaner than any of the other answers.

Give the input a padding-left to make space for the prefix. And position the a prefix element over that space.

.prefix {
  position: relative;
  right: -3px;
  color: grey;
}

input.has-prefix {
  padding-left: 50px;
  margin-left: -50px
}

<span class="prefix">https://</span>
<input class="has-prefix" type="text">

Depending on how you want to align the <input> element, you can adjust the prefix's right position and the input's margin-left setting accordingly.

Solution 7 - Jquery

All tested!

$('#myUrl').keyup(function(e) {
  if (this.value.length < 7) {
    this.value = 'http://';
  } else if (this.value.indexOf('http://') !== 0) {
    this.value = 'http://' + String.fromCharCode(e.which);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="myUrl">URL:</label>
<input id="myUrl" type="text" value="http://">

Solution 8 - Jquery

This is just me playing around, but you can make a fake extension of the textbox. This example basically chops off the left border of the textbox and concatenates a fake textbox to the left.

Works only in Chrome AFAICT. You will have to add conditional stylesheets for each browser if you decide on this method.

http://jsfiddle.net/G9Bsc/1/

Solution 9 - Jquery

Pure CSS based solution we did make div wrapper and span input combination, please do refer follows

.lable {
  background-color: #dedede;
  width: 50%;
  padding: 15px;
  border: 1px solid #FF0000;
  -moz-border-radius: 5px;
  border-radius: 5px;
  padding: 5px 5px;
}
.snehainput {
  background-color: #dedede;
  border-left: 1px solid #000000;
  border-right: 0px;
  border-top: 0px;
  border-bottom: 0px;
  padding: 2px 5px;
  color: #666666;
  outline: none;
}

<div class="lable">
  <span class="prefix">971</span>
  <input class="snehainput" type="text" value="" />
</div>

Solution 10 - Jquery

There is a way to do this in javascript, but I'm afraid it is more trouble than it's worth.

However, if you're sure the text won't change over time, you can use a CSS background image for the text input that is an image of your text 'http://'. Then you can just add some padding-left until the user's input starts right next to the end of your image.

Solution 11 - Jquery

If you insist on 'http://' being the the default value, add the "value" attribute to the input tag:

<input id="url" type="text" value="http://">

Allow users to remove it if they wish, yet validate when the form is sent. (jQuery's validation plugin)

Solution 12 - Jquery

Not so clean but it doesn't let users remove your prefix

<input type="text" name="membership_num" value="0201" id="membership_num">  

//prefix
$(document).on('keyup','#membership_num',function(){
  var original = $('#membership_num').val().split('');
  original[0] = "0";
  original[1] = "2";
  original[2] = "0";
  original[3] = "1";
  $('#membership_num').val(original.join(''));
});

Solution 13 - Jquery

This is for the textbox, if user forgot to put http:// then it will add otherwise it won't.

if (this.value.length > 7) {
if(this.value.substring(0, 7)== "http://"  || this.value.substring(0, 
8)== "https://"){
    this.value = this.value;
    }
    else{
    	  	this.value = "http://" + this.value;
    }

Solution 14 - Jquery

Material UI Inputs can accept an input adornment prop for prefixes or suffixes:

https://material-ui.com/api/input-adornment/

<TextField
      label="With normal TextField"
      id="standard-start-adornment"
      className={clsx(classes.margin, classes.textField)}
      InputProps={{
        startAdornment: <InputAdornment position="start">Kg</InputAdornment>,
      }}
    />
    <FormControl className={clsx(classes.margin, classes.withoutLabel, classes.textField)}>
      <Input
        id="standard-adornment-weight"
        value={values.weight}
        onChange={handleChange('weight')}
        endAdornment={<InputAdornment position="end">Kg</InputAdornment>}
        aria-describedby="standard-weight-helper-text"
        inputProps={{
          'aria-label': 'weight',
        }}
      />

Solution 15 - Jquery

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.

Solution 16 - Jquery

$("input").keyup(function(e) {
  var oldvalue = $(this).val();
  var field = this;
  if (field.value.indexOf('http://') === -1 &&
    field.value.indexOf('https://') === -1) {
    $(field).val('http://');
  }
});

<input type="text" value='http://'>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

Solution 17 - Jquery

UPDATE: Guillaumesm's answer to Ecmascript 5:

Form.prototype.set_HttpPrefix = function (e) {
    if (e.data.$url.val().length < 7) {
        e.data.$url.val('http://')

    }    
    else if (e.data.$url.val().indexOf('http://') !== 0) {
        e.data.$url.val('http://' + String.fromCharCode(e.which)) 
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMindtreeView Question on Stackoverflow
Solution 1 - JqueryguillaumesmoView Answer on Stackoverflow
Solution 2 - JqueryLPChipView Answer on Stackoverflow
Solution 3 - JqueryGuffaView Answer on Stackoverflow
Solution 4 - JqueryDo AsyncView Answer on Stackoverflow
Solution 5 - JqueryPaul D. WaiteView Answer on Stackoverflow
Solution 6 - JqueryH KView Answer on Stackoverflow
Solution 7 - JqueryDarshit GajjarView Answer on Stackoverflow
Solution 8 - JqueryBlenderView Answer on Stackoverflow
Solution 9 - Jqueryuser1208396View Answer on Stackoverflow
Solution 10 - JquerytypeofView Answer on Stackoverflow
Solution 11 - JqueryrobozevelView Answer on Stackoverflow
Solution 12 - JqueryHimanshu SainiView Answer on Stackoverflow
Solution 13 - JqueryAsteriskView Answer on Stackoverflow
Solution 14 - JqueryJarView Answer on Stackoverflow
Solution 15 - JqueryDVKView Answer on Stackoverflow
Solution 16 - JqueryKlogo Gibson SelasiView Answer on Stackoverflow
Solution 17 - JqueryAngie AlejoView Answer on Stackoverflow