I need to add a '%'
symbol to the values entered into an input field. How can I do this using javascript only (not using jquery or other libs).
Example:
When I type "34" in the input field it should appear as "34%". Below is my input field sample:
<input type="text" id="amountId" onkeydown="change(event)" />
I need to add a '%'
symbol to the values entered into an input field. How can I do this using javascript only (not using jquery or other libs).
Example:
When I type "34" in the input field it should appear as "34%". Below is my input field sample:
<input type="text" id="amountId" onkeydown="change(event)" />
Share
Improve this question
asked Jun 11, 2017 at 16:53
nanospecknanospeck
3,5583 gold badges39 silver badges45 bronze badges
1
- do you wish the value to remain as 34 from the perspective of the form, or to be 34%? did you check the CSS only answer given here: stackoverflow./a/38520939/4007992 – ExoticChimp Commented Jun 11, 2017 at 16:57
4 Answers
Reset to default 4With a text field, that's relatively easy:
var input = document.getElementById('amountId');
input.addEventListener('blur', function () { // as soon as the input element loses focus, "%" is appended
input.value += '%';
});
<input type="text" id="amountId" />
However, there are a few things to note:
- It's not very user-friendly (if the user wants to change the value from 34 to 35, he or she has to delete the
%
character). - If the user inputs non-numeric values (
foobar
),%
also is appended.
For these reasons, I would just use a <input type="number">
:
<input type="number" min="0" max="100">%
I was able to e up with a solution by extensive use of event.preventDefault()
to prevent non-numberic character from printing and re-rendering the value in each key down.The number part of the value is parsed first and I append the pressed key value and % symbol at the end of the string. Sorry I can't share the full solution because it's logic is customized further for my specific usecase.
$('#amountId').blur(function(e){
var thisVal = this.value.replace(/\D/g, '');
$('#amountId').val(thisVal + '%');
});
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="amountId" onkeydown="change(event)" />
For anyone reading in the future: If you want to do what PeterMader suggested without adding a new "%" everytime you edit the inputfield, just do
var input = document.getElementById('amountId');
input.addEventListener('blur', function () {
input.value += '%';
});
input.addEventListener('keydown', function () {
rente.value = rente.value.replace('%', '') //This simply removes the "%" when you start typing again
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745104889a4611498.html
评论列表(0条)