Home > Back-end >  How to loop through,and evaluate sequentially named form elements with JavaScript
How to loop through,and evaluate sequentially named form elements with JavaScript

Time:07-07

I need to loop through, and evaluate the values of form elements by calling the function updt().

const updt = () => {
  let f = document.forms['myform'];

  f.r1c3.value = f.r1c1.value * f.r1c2.value;
  f.r2c3.value = f.r2c1.value * f.r2c2.value;
  f.r3c3.value = f.r3c1.value * f.r3c2.value;
}
<form id="myform" name="myform">
  <input type="text" name="r1c1" onchange="updt()">
  <input type="text" name="r1c2">
  <input type="text" name="r1c3">
  <input type="text" name="r2c1">
  <input type="text" name="r2c2">
  <input type="text" name="r2c3">
  <input type="text" name="r3c1">
  <input type="text" name="r3c2">
  <input type="text" name="r3c3">
</form>

My wish is to loop through the form elements, and fill c3 with the product of c1 and c2. Here is my attempt...

  for (var n=1;  n<=3; n  ) {
    `f.r${n}c3.value` =  `f.r${n}c1.value` * `f.r${n}c2.value`;
  }

The above loop did not work.

eval() worked for the right side. But the left side still did not work.

The reason I want to loop, is because there are about 20 lines, not just the 3 shown above. So I want to shorten the code somehow.

Any thoughts?

TIA

CodePudding user response:

This just produces a string, nothing more:

`f.r${n}c3.value`

So it isn't executable code. And eval can help, but there's a simpler way to do this. You can use a string to access property names of an object. And since only that one property name is changing, the rest can be code like any other. For example:

f[`r${n}c3`].value

So the whole line would be:

f[`r${n}c3`].value =  f[`r${n}c1`].value * f[`r${n}c2`].value;

CodePudding user response:

You can simply use bracket notation for accessing properties dynamically, like this:

for (var n=1;  n<=3; n  ) {
    f[`r${n}c3`].value =  f[`r${n}c1`].value` * f[`r${n}c2`].value;
}

CodePudding user response:

I'm posting an answer just because i made a one-liner and it looks great :)

  1. The spread operator on a form gives you all the inputs of a form
  2. Then i filter them to get only the rc3 inputs(result)
  3. Finally i set each value with the other two inputs of the row
const myform = document.forms['myform']

const setFormValue = () => 
    [...myform]
    .filter(input => /^r\dc3$/.test(input.name))
    .forEach(input => input.value = Number(myform[input.name.replace(/\d$/, '1')].value) * Number(myform[input.name.replace(/\d$/, '2')].value))

myform.addEventListener('submit', e => {
    e.preventDefault();
    setFormValue()
});
  • Related