如何向HTML输入字段添加不可移动的前缀?

时间:2022-01-06 08:00:46

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?

使用jQuery,如何将http://的默认值添加到无法删除的输入字段中,但仍然允许您在输入字段后输入URL ?

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

默认值:http:// Url:http://www.domain.name

15 个解决方案

#1


25  

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/

http://jsfiddle.net/J2BKU/

#2


13  

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:

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:

HTML:

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

#3


7  

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.

我遇到了同样的问题,不用jquery就解决了,只需要简单的CSS和HTML。这个解决方案看起来很优雅,用户可以立即理解它是如何工作的。

Use the following code in your html:

在html中使用以下代码:

(short title): 
<span class="textbox"> 
    http://
    <input type="text" name="url" autofocus />
</span>

and as CSS you use:

作为CSS你使用:

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

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

结果将是这样的(复制了我的脚本的结果,所以它不会说http://):

如何向HTML输入字段添加不可移动的前缀?

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

注意,您只需要在脚本中预置http://,但这将使其工作完美。

#4


4  

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.

只能在Chrome上使用。如果您决定使用此方法,那么您必须为每个浏览器添加条件样式表。

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

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

#5


4  

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

#6


4  

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

我见过一些web表单在字段之外包含这个值,例如。

<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.

但是,如果您已经下定决心通过JavaScript强制执行该值(请记住,用户可以关闭JavaScript),那么可以编写一个函数,每次用户在字段中键入时触发该函数,如果字段不存在,则将http://添加到字段的开头。如。

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

#7


3  

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

基于纯CSS的解决方案,我们确实做了div包装和span输入组合,请参考下面的内容。

.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>

#8


2  

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

在javascript中有一种方法可以做到这一点,但恐怕这比它的价值更麻烦。

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.

但是,如果你确定文本不会随时间变化,你可以使用CSS背景图像来输入文本输入,这是你的文本“http://”的图像。然后你可以添加一些空格-左直到用户的输入在你的图像的末尾开始。

#9


2  

Check this format util and a prefix implementation for it:

检查此格式util和前缀实现:

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

#10


1  

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

如果您坚持使用“http://”作为默认值,则在输入标签中添加“value”属性:

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

允许用户删除它,如果他们愿意,但验证什么时候发送表单。(jQuery验证插件)

#11


1  

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

#12


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

我不确定关于jQuery,但在平原JS,你可以尝试检测磁场变化,如果变化时破坏了前缀,将其重新添加(不是100%万无一失——如果你想要,你必须把外的“http://”在输入字段并添加后来以编程方式):

<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.

请注意,这种奇怪的行为会让用户感到困惑,没有事先明确的解释,或者弹出窗口(可能是非模态的)解释你为他纠正了错误。

#13


0  

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

#14


0  

UPDATE: Guillaumesm's answer to Ecmascript 5:

更新:Guillaumesm对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)) 
    }
}

#15


0  

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

这是针对文本框的,如果用户忘记输入http://,那么它就会添加,否则就不会添加。

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

#1


25  

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/

http://jsfiddle.net/J2BKU/

#2


13  

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:

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:

HTML:

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

#3


7  

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.

我遇到了同样的问题,不用jquery就解决了,只需要简单的CSS和HTML。这个解决方案看起来很优雅,用户可以立即理解它是如何工作的。

Use the following code in your html:

在html中使用以下代码:

(short title): 
<span class="textbox"> 
    http://
    <input type="text" name="url" autofocus />
</span>

and as CSS you use:

作为CSS你使用:

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

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

结果将是这样的(复制了我的脚本的结果,所以它不会说http://):

如何向HTML输入字段添加不可移动的前缀?

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

注意,您只需要在脚本中预置http://,但这将使其工作完美。

#4


4  

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.

只能在Chrome上使用。如果您决定使用此方法,那么您必须为每个浏览器添加条件样式表。

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

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

#5


4  

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

#6


4  

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

我见过一些web表单在字段之外包含这个值,例如。

<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.

但是,如果您已经下定决心通过JavaScript强制执行该值(请记住,用户可以关闭JavaScript),那么可以编写一个函数,每次用户在字段中键入时触发该函数,如果字段不存在,则将http://添加到字段的开头。如。

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

#7


3  

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

基于纯CSS的解决方案,我们确实做了div包装和span输入组合,请参考下面的内容。

.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>

#8


2  

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

在javascript中有一种方法可以做到这一点,但恐怕这比它的价值更麻烦。

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.

但是,如果你确定文本不会随时间变化,你可以使用CSS背景图像来输入文本输入,这是你的文本“http://”的图像。然后你可以添加一些空格-左直到用户的输入在你的图像的末尾开始。

#9


2  

Check this format util and a prefix implementation for it:

检查此格式util和前缀实现:

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

#10


1  

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

如果您坚持使用“http://”作为默认值,则在输入标签中添加“value”属性:

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

允许用户删除它,如果他们愿意,但验证什么时候发送表单。(jQuery验证插件)

#11


1  

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

#12


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

我不确定关于jQuery,但在平原JS,你可以尝试检测磁场变化,如果变化时破坏了前缀,将其重新添加(不是100%万无一失——如果你想要,你必须把外的“http://”在输入字段并添加后来以编程方式):

<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.

请注意,这种奇怪的行为会让用户感到困惑,没有事先明确的解释,或者弹出窗口(可能是非模态的)解释你为他纠正了错误。

#13


0  

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

#14


0  

UPDATE: Guillaumesm's answer to Ecmascript 5:

更新:Guillaumesm对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)) 
    }
}

#15


0  

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

这是针对文本框的,如果用户忘记输入http://,那么它就会添加,否则就不会添加。

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