Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q809 How do I display the value of each text field using a for loop?

You are here: irt.org | FAQ | JavaScript | Form | 3.2 | Q809 [ previous next ]

If you know the names of text fields - or perhaps they all contain the same text sequence within the name then you can perform this by searching through the forms elements array:

<form name="formName">
<input type="text" name="myTextA" value="apple">
<input type="text" name="myTextB" value="orange">
<input type="text" name="myTextC" value="banana">
<input type="text" name="myTextD" value="pear">
<input type="text" name="myTextE" value="peach">
<input type="text" name="myTextF" value="grape">

<input type="button" onClick="cycle()" value="Check">

<br>

<input type="text" name="answer" size="60">

</form>

<script language="JavaScript"><!--
function cycle() {
    var answer = '';
    for (var i = 0; i<document.formName.elements.length; i++) {
        if ((document.formName.elements[i].name.indexOf('Text') > -1)) {
            answer += document.formName.elements[i].value + ' ';
        }
    }
    document.formName.answer.value = answer;
}
//--></script>

If you add the following script on the end of the previous example, then browsers that support JavaScript 1.1 will use the type property of each form field and will only output the value where the type property is 'text':

<script language="JavaScript1.1"><!--
function cycle() {
    var answer = '';
    for (var i = 0; i<document.formName.elements.length; i++) {
        if ((document.formName.elements[i].type == 'text')) {
            answer += document.formName.elements[i].value + ' ';
        }
    }
    document.formName.answer.value = answer;
}
//--></script>

If however, you require a solution that cannot rely on the name of the text fields containing a string you can search for, then the following example creates an array of form field names which is then used when retriving the value of the required form fields:

<script language="JavaScript"><!--
function makeArray() {
    this[0] = makeArray.arguments.length;
    for (i = 0; i<makeArray.arguments.length; i++)
        this[i+1] = makeArray.arguments[i];
}

var fieldNames  = new makeArray('myTextA','myTextB','myTextC','myTextD','myTextE','myTextF');

function cycle() {
    var answer = '';
    for (var i = 0; i<fieldNames[0]; i++) {
        answer += document.formName.elements[fieldNames[i]].value + ' ';
    }
    document.formName.answer.value = answer;
 }
//--></script>

Feedback on 'Q809 How do I display the value of each text field using a for loop?'

©2018 Martin Webb