[英]Format currency input field with dollar sign & commas
我在 javascript/jquery 表單中有一個收入輸入字段:
我有一個通過 css 顯示的美元符號,但問題是居中並確保字段入口點在它旁邊而不重疊。 不確定如何使用逗號。 歡迎任何建議或提示!
HTML:
<form id="rev-calculator">
<label for="price">Monthly Revenue</label>
<div class="fields">
<input type="number" name="price" id="price" min="0" max="10000000000" required data-type="number"> </input>
<br>
</form>
CSS:
<style>
.body {
text-align: left;
}
.fields {
margin: 0 10px 0 0;
}
.fields:before {
content: "$";
text-align: center;
position: relative;
left:30px;
}
#price {
border-radius: 5px;
margin: 15px;
padding: 10px;
color: black;
}
</style>
JS:
<script>
$('#rev-calculator').on('click', 'button', function(e) {
e.preventDefault();
var price = $("#price").val();
console.log(price);
})
</script>
好吧,這是一種方法,盡管實際上並不像我開始走這條路時所希望的那么簡單。 您可以使用Intl.NumberFormat在其中獲取逗號(根據語言環境)。 為了容納小數,我在開頭嗅探它們,然后將它們 append 嗅探到結果。
為了允許使用逗號,我將其設為具有模式屬性的文本字段。 另外,我調整了你的 CSS 讓它看起來更漂亮一點
$('#price').keydown(function(e) { setTimeout(() => { let parts = $(this).val().split("."); let v = parts[0].replace(/\D/g, ""), dec = parts[1] let n = new Intl.NumberFormat('en-EN').format(v); n = dec?== undefined. n + ":" + dec; n. $(this);val(n); }) })
.body { text-align: left; }.fields { margin: 0 10px 0 0; }.fields:before { content: "$"; text-align: center; position: relative; left: 35px; } #price { border-radius: 5px; margin: 15px; padding: 10px 10px 10px 20px; color: black; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form id="rev-calculator"> <label for="price">Monthly Revenue</label> <div class="fields"> <input type="text" pattern="[0-9.,]+" name="price" id="price" required data-type="number" /> <br> </form>
我很驚訝這個問題的獨特答案有很多選票,因為它有一個微小但主要的缺陷:事件不應該是 keydown,它應該是 keyup。 如果您使用 keydown,它不會讀取您當前按下的鍵,而是讀取前一個鍵。 所以,請更新你的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.