我有一个输入字段
<input type="text" value="$">
我需要将$
符号固定在输入的第一位,而不考虑输入内部的数字或字符
目前,我正在$
函数的外部添加onChange
符号
value = '$' + value
基本上,用户不应清除$
符号。它应该是固定的。如何实现呢?
我正在使用javascript和React。
答案 0 :(得分:1)
在输入更改时,您可以首先从值中删除所有出现的$
。然后在值前加上$
。
尝试以下操作:
function inputValue(el){
el.value = el.value.replace(/[$+]/g, ''); //replace all $ with empty string
el.value = '$' + el.value; //prepend $ to the input value
}
<input type="text" value="$" oninput="inputValue(this)">
如果只允许数字和点(.
),请使用:
el.value = el.value.replace(/[^0-9.]/g, '');
答案 1 :(得分:0)
您将输入字段放在div
中。这个div
显示了您输入字段的占位符,看起来好像里面实际上存在一个$
符号,该符号不可编辑。
.foo {
padding-left: 20px;
}
.placeholder
{
position: relative;
}
.placeholder::after
{
position: absolute;
left: 5px;
top: 1px;
content: attr(data-placeholder);
pointer-events: none;
opacity: 0.6;
}
<div class="placeholder" data-placeholder="$">
<input type="text" class="foo" value="">
</div>
<button type="button" onclick="alert(document.getElementsByClassName('foo')[0].value)">
Get Value
</button>