Get the value of a dynamic input element in a form object

My question is: how do I refer to the dynamic "name" of an input element in a form?

For example, with the following HTML:

<form>
    <input type="text" name="qty1" value="input1" />
     <input type="text" name="qty2" value="input2" />
     <input type="text" name="qty3" value="input3" />

    <input type="submit" value="Submit" onClick="checkVal(this.form); return false;" />
</form>

Javascript:

function checkVal(form) {
    for (var i = 1; i <= 3; i++) {
        alert(form.qty+i.value);  // Here where my problem is..
    }
}

The above javascript is not working. The message displays NaN.

How to refer to qty1, qty2and qty3in the loop for, using a variable i?

Here's jsfiddle: http://jsfiddle.net/MRzWf/

+4
source share
5 answers

Use parenthesis designation

 form["qty" + i].value

Demo

+6
source

Just log in as a dictionary

http://jsfiddle.net/MRzWf/2/

 alert(form["qty"+i].value);
+3
source

form.qty+i,

, index .

There is another way to check the input value. Here is one.

  function checkVal(form) {
    var allInputs = document.getElementsByTagName('input');
    for (var i = 0; i < 3; i++) {
          if(allInputs[i].type == 'text'){
                alert(allInputs[i].value);  
          }
    }
}

Demo

0
source

Try it. It works for the above problem.

function checkVal(form) {
for (var i = 0; i < 3; i++) {
    alert(document.getElementsByTagName("input")[i].value);
}  }
0
source

Standard solution

Usage: form.elements[]should work in all browsers ..

function checkVal(form) {
    for (var i = 1; i <= 3; i++) {
        alert(form.elements["qty"+i].value);

        /* OR using dynamic name variable
        var ename = "qty"+i;
        alert(form.elements[ename].value);
        */
    }
}
0
source

Source: https://habr.com/ru/post/1527003/


All Articles