代码之家  ›  专栏  ›  技术社区  ›  user13286

jQuery-设置输入的值和文本

  •  0
  • user13286  · 技术社区  · 7 年前

    $(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

    2 回复  |  直到 7 年前
        1
  •  1
  •   Tyler Roper    7 年前

    如果你把你的输入包装成 <span> $ value . 使用这个方法,您只需要将您的输入包装在 <span class="currency"></span> 剩下的将通过CSS处理。


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

    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>

    -在输入的左边创建一个伪元素“indicator”

    var价格=3.25;
    $('#price').val(价格);
    .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;
    }
    <脚本src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></脚本>
    <span class=“currency”>&书信电报;输入type=“text”id=“price”/></跨度>
        2
  •  2
  •   Manoj Mathew    7 年前

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

    <lable>$</label><input id="price" type="text" />
    
    推荐文章