【问题标题】:jQuery - Set value AND text of inputjQuery - 设置值和输入文本
【发布时间】:2018-09-20 03:10:41
【问题描述】:

我有一个表单,我正在使用 API 自动填充价格字段。我想做的是将输入的值(提交的内容)设置为数字,但在实际输入字段中我希望它以价格格式显示。

$(function() {
  var price = 3.25;
  $('input').val(price);
  $('input').text('$' + price);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="price" type="text" />

在上面的示例中,我将如何使提交的值只是原始数字3.25,但在实际输入字段中显示为$3.25

【问题讨论】:

  • 你不能因为text()函数不适用于输入。为什么不在 $&lt;input id="price" type="text" /&gt; 之类的文本字段前面放一个 $
  • 根据我的经验,这种事情的常见方法是将数字部分放在一个跨度或带有标识符的东西中,并且 $ 出现在该元素之前。然后你的所有逻辑就是设置跨度。但在用户看来,$ 似乎属于金额。
  • Bootstrap 和可能的其他库也有很好的小方法将 $ 附加到输入,因此它不是值的一部分,但看起来并不垃圾。 getbootstrap.com/docs/4.1/components/input-group

标签: jquery input


【解决方案1】:

您需要文本框中的“$”吗?

您最好在 html 中添加“$”作为标签,因为它始终是价格字段。

<lable>$</label><input id="price" type="text" />

【讨论】:

    【解决方案2】:

    如果您将输入包装在 &lt;span&gt; 中,您可以在其上添加一些样式,使输入看起来像前面有 $,而不会影响其 value。使用这种方法,您只需将输入包装在 &lt;span class="currency"&gt;&lt;/span&gt; 中,其余的将通过 CSS 处理。


    Plain - 将伪元素绝对定位到左填充输入中

    var price = 3.25;
    $('#price').val(price);
    .currency {
      position: relative;
      font-size: 14px;
    }
    
    .currency::before {
      position: absolute;
      display: inline-block;
      content: '$';
      left: 3px;
      top: 0;
    }
    
    .currency input[type=text] {
      padding-left: 9px;
      box-sizing: border-box;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <span class="currency"><input type="text" id="price" /></span>

    “Bootstrap Style” - 在输入左侧创建一个伪元素“指示器”

    var price = 3.25;
    $('#price').val(price);
    .currency {
      font-size: 15px;
    }
    
    .currency::before {
      display: inline-block;
      content: '$';
      padding: 4px 6px;
      border: 1px solid #ccc;
      background-color: #efefef;
      font-weight: bold;
    }
    
    .currency > input[type=text] {
      padding: 5px;
      border: 1px solid #ccc;
      border-left: 0;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <span class="currency"><input type="text" id="price" /></span>

    【讨论】:

      猜你喜欢
      • 2014-04-01
      • 2012-05-23
      • 1970-01-01
      • 1970-01-01
      • 2016-04-26
      • 1970-01-01
      • 2013-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多