How to Use Dynamic Field Names in JavaScript for Currency Formatting?

Hey everyone,

I’m trying to create a JavaScript function that removes commas from currency values. Here’s what I’ve got so far:

function formatCurrency(fieldName, value) {
  const noCommas = value.replace(/,/g, '');
  document.myForm[fieldName].value = noCommas;
}

I’m calling it like this:

<input onblur="formatCurrency(this.name, this.value)" />

The problem is, I can’t seem to make the field name dynamic. When I try to use the passed-in fieldName, I get an error saying it’s not valid.

I know the field name and value are being passed correctly, but I can’t figure out how to use them in the function. Any ideas on how to make this work with any field I pass in?

Thanks for your help!

I’ve encountered similar issues with dynamic field names before. One approach that worked well for me was using the getElementById() method instead of directly accessing the form. Here’s a modified version of your function that should solve the problem:

function formatCurrency(fieldName, value) {
  const noCommas = value.replace(/,/g, '');
  document.getElementById(fieldName).value = noCommas;
}

This assumes your input fields have unique IDs matching their names. If not, you might need to adjust your HTML slightly. Also, make sure to call the function like this:

<input id="fieldName" onblur="formatCurrency(this.id, this.value)" />

This method is more reliable and works across different browsers. Let me know if you run into any issues!

While the previous answers offer valid solutions, there’s another approach worth considering. You can use the querySelector method to target the specific input field within your form. Here’s how you could modify your function:

function formatCurrency(fieldName, value) {
  const noCommas = value.replace(/,/g, '');
  document.querySelector(`form[name='myForm'] [name='${fieldName}']`).value = noCommas;
}

This method allows you to keep your HTML as is, without needing to add IDs. It’s particularly useful when dealing with dynamically generated forms or when you have multiple forms on a page. Just ensure your form has a name attribute set to ‘myForm’. This approach combines flexibility with specificity, making your code more robust across different scenarios.

hey TomDream42, try using bracket nottion instead of dot nottion. change ur func to:

function formatCurrency(fieldName, value) {
  const noCommas = value.replace(/,/g, '');
  document.myForm[fieldName].value = noCommas;
}

that shld work for u, hope it helps!