I am very new to this – how can I add a dollar sign using an event listener? Currently I have:
let dol = document.querySelector('#dollar');
dol.addEventListener('keyup', function(e) { {
dol.value = "$" + dol.value;
}
});
But this is adding a dollar sign for every digit.
I only need the one in front.
2
Answers
Don’t use JS, you don’t need it. Amounts are numbers, and should only ever be numbers. Only the presentation needs a dollar sign, which is what we have HTML and CSS for.
Use a span for the currency symbol, and then use CSS to show the appropriate one:
Or you can set an
:after
on the labels and not have a dedicated currency indicating element:Just note that you can’t set a
:before
on the input elements, even though that would be the most "logical" place to put them, because :before and :after pseudo-classes are treated as sort-of-kind-of child content, and input elements can’t have child content, so it’ll do nothing (same for<img>
for example. If it’s a "void" element, :before and :after won’t work).