开发者

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://):

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

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>


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" />


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;
    }
});


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.


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://">


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/


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>


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)


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.


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(''));
});


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;
    }


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',
        }}
      />


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.


$("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>


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)) 
    }
}


We can use input pattern

    <input
      placeholder="https://www.website.com"
      value={variable}                        //state variable
      onInput={(e) => handleInput(e)}
      pattern="(^h$)|(^ht$)|(^htt$)|(^http$)|(^https$)|(^https:$)|(^https:\/$)|(^https:\/\/.*)"
    />

    const handleInput = (e) => {
      setVariable(e.target.validity.valid ? e.target.value : variable);
    };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜