html5 input for money/currency

前端 未结 7 1428
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 01:55

I seem unable to work out what to use for accepting monetary values on a form.

I have tried...



        
相关标签:
7条回答
  • 2020-12-08 02:24

    var currencyInput = document.querySelector('input[type="currency"]')
    var currency = 'USD' // https://www.currency-iso.org/dam/downloads/lists/list_one.xml
    
     // format inital value
    onBlur({target:currencyInput})
    
    // bind event listeners
    currencyInput.addEventListener('focus', onFocus)
    currencyInput.addEventListener('blur', onBlur)
    
    
    function localStringToNumber( s ){
      return Number(String(s).replace(/[^0-9.-]+/g,""))
    }
    
    function onFocus(e){
      var value = e.target.value;
      e.target.value = value ? localStringToNumber(value) : ''
    }
    
    function onBlur(e){
      var value = e.target.value
    
      var options = {
          maximumFractionDigits : 2,
          currency              : currency,
          style                 : "currency",
          currencyDisplay       : "symbol"
      }
      
      e.target.value = value 
        ? localStringToNumber(value).toLocaleString(undefined, options)
        : ''
    }
    input{
      padding: 10px;
      font: 20px Arial;
      width: 70%;
    }
    <input type='currency' value="123" placeholder='Type a number & click outside' />

    0 讨论(0)
提交回复
热议问题