[英]How can I add an unremovable suffix to an HTML input field
Using jQuery, how can I add a default suffix of , Demos
into an input field that can't be removed, and that still allows you to type a content before suffix? 使用jQuery,如何将默认后缀
, Demos
添加到无法删除的输入字段中,并且仍然允许您在后缀之前键入内容?
Default: ,Demos 默认值:,Demos
Content: myText, Demos 内容:myText,演示
Any help would be precious! 任何帮助都是宝贵的!
Here's a code that adds a suffix on change of an input field using Jquery: 以下是使用Jquery更改输入字段时添加后缀的代码:
$('#input').on('change focus unfocus', function(){
var inputValue = $(this).val();
var suffix = ", Demos";
if(!(inputValue.indexOf(suffix) > -1)){
var newVal = inputValue + suffix;
$(this).val(newVal);
}else{
var suffixLength = inputValue.indexOf(suffix) + suffix.length;
var len = inputValue.length - suffixLength;
if(len >0){
$(this).val((inputValue.slice(suffixLength, inputValue.lenght))+suffix);
}
}
}); });
Here's a JSFiddle 这是一个JSFiddle
You might have to consider what you want to do if a change is made after the suffix already is applied, either delete everything or keep everything but remove all the chars after the suffix. 如果在应用后缀后进行了更改,您可能必须考虑要做什么,要么删除所有内容,要么保留所有内容,但删除后缀后的所有字符。 Also you might want to use a validation pattern to check if the suffix is applied.
另外,您可能想使用验证模式来检查是否应用了后缀。
EDIT: JSFIddle and code are updated to make the suffix pretty much unremovable. 编辑: JSFIddle和代码已更新,以使后缀几乎不可移动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.