jQuery 如何向 HTML 输入字段添加不可删除的前缀?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4535963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:25:40  来源:igfitidea点击:

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

jqueryhtml

提问by Mindtree

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://
网址:http: //www.domain.name

回答by guillaumesmo

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/

回答by LPChip

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 中使用以下代码:

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

结果看起来像这样(从我的脚本中复制了结果,所以它没有说 http://):

enter image description here

在此处输入图片说明

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

请注意,您只需在脚本中添加 http:// 即可,但这将使其完美运行。

回答by Guffa

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>

回答by Do Async

Check this format utiland a prefix implementation for it:

检查此格式工具及其前缀实现:

  • no glitching
  • flexibility with regex
  • any inputevent (keyboard, mouse, drag-n-drop, etc.)
  • universal utility (extra formatters can be added)
  • bug tested
  • 没有故障
  • 正则表达式的灵活性
  • 任何input事件(键盘鼠标拖放等)
  • 通用实用程序(可以添加额外的格式化程序)
  • 错误测试

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

回答by Paul D. Waite

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.

但是,如果您一心想通过 JavaScript 强制执行该值(请记住,用户可以关闭 JavaScript),您可以编写一个函数,每次用户在该字段中键入时都会触发该函数,并添加http://到该字段的开头如果它不在那里。例如

HTML:

HTML:

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

?JavaScript:

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

回答by Darshit Gajjar

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

回答by Blender

This is just me playing around, but you can make a fakeextension 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 AFAICT。如果您决定采用此方法,则必须为每个浏览器添加条件样式表。

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

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

回答by user1208396

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

基于纯 CSS 的解决方案我们确实制作了 div 包装器和跨度输入组合,请参考以下内容

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

回答by typeof

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 imagefor 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://”的图像。然后你可以添加一些 padding-left 直到用户的输入在你的图像末尾开始。

回答by robozevel

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 的验证插件