【问题标题】:How to add dollar sign to input field without affecting the value of input?如何在不影响输入值的情况下将美元符号添加到输入字段?
【发布时间】:2018-11-11 03:41:37
【问题描述】:

如何将 $ 添加到以下输入中:

<td class="td10"><input type='text' class='form-control' id="boqRate" name="boq[boqRate]"></td>

【问题讨论】:

  • 将输入框包裹在div 中,并使用CSS 创造一种在文本框中以$ 作为前缀的错觉。搜索教程,已经有很多可用的了。 AFAIK,别无他法。

标签: javascript html css ejs


【解决方案1】:

试试这个。我添加了带有position:absolute 的span 元素。

.prefix {
  margin-right: -10px;
  position: absolute;
}

.my-input {
  padding-left: 5px;
}
&lt;td class="td10"&gt;&lt;span class="prefix"&gt;$&lt;/span&gt;&lt;input class="my-input" type='text' class='form-control' id="boqRate" name="boq[boqRate]"&gt;&lt;/td&gt;

【讨论】:

    【解决方案2】:

    这应该可行:

    let input = document.getElementById("name");
    
    input.addEventListener("keydown", () => {
      let inputValue = input.value;
      if (inputValue) {
        if (inputValue.charAt(0) === "$") {
          inputValue = inputValue.substring(1);
        }
      }
      let newValue = `$${inputValue}`;
      input.value = newValue;
    });
    &lt;input id="name" /&gt;

    希望对你有帮助!

    【讨论】:

    • 在输入框获得焦点的同时按下 键。如果我事先不知道,我最终会得到 $$。
    • 最好使用keyup 而不是keydown
    • @Barmar 你能详细说明一下吗?
    • 我认为这可能会解决 Esaith 提到的问题,因为它在用户键入 $ 之后运行。
    • @Barmar 也许但是当您按退格键时确实会产生问题。在这里试试:jsfiddle.net/m5v1a5q1(带键盘)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多