Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add a dollar sign with an Event Listener

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

eten : Just check with dol.value.startsWith("$")

let dol = document.querySelector('#dollar')
  ;
dol.addEventListener('keyup', e =>
  {
  if (!dol.value.startsWith('$'))
    dol.value = "$" + dol.value; 
  });
label {
  margin      : .6rem;
  display     : block;
  font-size   : .8rem;
  font-weight : bold;
  }
label * {
  box-sizing : border-box;
  display    : block;
  font-size  : 1rem;
  width      : 16rem;
  padding    : .2rem .3rem;
  }
<label>
  input for dollars...
  <input id="dollar" type="text" >
</label>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading