javascript - 如何将静态文本添加到输入值

标签 javascript php

我有一个输入元素,我想要做的是当用户键入时,此静态文本将始终出现在用户输入之后。

h "staticTextHere"
hello "staticTextHere"
hello world "staticTextHere"

我尝试了一些技术,但这里有很多问题。有什么想法如何实现这一目标吗?

这是我的代码;

<input type="text" id="staticTextId" name="staticTextName" ..... />

还有js;

.on('keydown', function (event) {
         var textLength = document.getElementById($id).value.length;
         document.getElementById($id).value = document.getElementById($id).value.substr(0,textLength - staticText.length) + staticText;
 });

最佳答案

纯 JS 版本:Demo online

jQuery:Demo online

document.getElementById("staticTextId").addEventListener('keyup', function(){
    var str = this.value;
    var suffix = " static text";

    if(str.search(suffix) === -1){
        str += suffix;
    }

    var actualLength = str.length - suffix.length;

    // set the value
    this.value = str.substr(0,actualLength) + suffix;

    // set cursor position
    this.setSelectionRange(actualLength,actualLength);    
});

关于javascript - 如何将静态文本添加到输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27548894/

相关文章:

用于 usort 的 PHP 附加参数

javascript - Firebase DB - 如何更新 Firebase 数据库中子项的特定值

javascript - 每个 session 仅 jQuery getJSON 一次

javascript - 过滤表数据并删除过滤列

javascript - 如何将我的对象与数据转换为dygraphs的输入?

php - 具有线程/回复的私有(private)消息系统

php - 如何创建一个 HTML/PHP 表单,其中文本输入字段并排水平对齐

PHP MYSQL事务返回错误SQLSTATE[HY000] : General error

php - 来自 PHP 数据的多个 MySQL 插入从 ajax 动态获取

javascript - React router dom无法获取页面