javascriptevent-listenerdollar-sign

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.


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>

    const myForm = document.querySelector('#my-Form')
      ;
    myForm.addEventListener('input', e =>  // for any input on form...
      {
      if ( ['money_1','money_2'].includes(e.target.name)
        && !e.target.value.startsWith('$')
        ){
        e.target.value = "$" + e.target.value.trim();
        
        if (e.target.value === '$') // you may need this one...
          e.target.value = '';  
        }
    
      });
    myForm.addEventListener('submit', e =>
      {
      e.preventDefault(); // disable form submision.
      
      // get values...
      console.clear();
      console.log('money_1 = ', myForm.money_1.value );
      console.log('money_2 = ', myForm.money_2.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;
      }
    <form id="my-Form">
      <label>
        input 1 for dollars...
        <input name="money_1" type="text" required >
      </label>
      <label>
        input 2 for dollars...
        <input name="money_2" type="text" required>
      </label>
      
      <button>submit</button>
    </form>