0

I'm learning JavaScript and trying to format my form's input text box to currency when updated. I'm using the below code, but it does not seem to work. Can someone help me out?

<input type="text" name="amount" onChange="currencyFormat(this.value, 'amount')" class="amount">
<script type="text/javascript">

function currencyFormat(num, fldname) {

 document.getElementsByName(fldname).value = '$' + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');

}     
</script>
user1609391
  • 445
  • 1
  • 9
  • 24
  • 1
    There is no `getElementByName`, it's `getElementsByName`. See https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName on how to use it – j08691 Mar 08 '20 at 20:54
  • @j08691 - why don't you put your answer into the answer? – Tomáš Pospíšek Mar 08 '20 at 20:56
  • @j08691 I updated my code to getElementsByName but it still does not work. I reviewed your suggested post, but don't see how this solves my problem. Can anyone help? – user1609391 Mar 08 '20 at 21:01
  • Every thing is fine with your code, the problem is toFixed() is supported only for integer values not the string. So change your code like below. `'$' + parseInt(num).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')` – Aravindan Venkatesan Mar 08 '20 at 21:02
  • @user1609391 If you read the dupe and the link to MDn you'd see that you need to access getElementsByName as an array, and I don't see you doing that – j08691 Mar 08 '20 at 21:06
  • @Aravind Sachin. Thank you so much! – user1609391 Mar 08 '20 at 21:15
  • @j08691, thank you I see now I need to adjust to `document.getElementsByName(fldname)[order].value = '$' + parseInt(num).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');` – user1609391 Mar 08 '20 at 21:19

0 Answers0