0

I've got various text fields with buttons beside each in a grid. When I click a button, it returns a value to a text field beside it. The problem is making it know which text field to return the data to. I've currently got it set up to pass a parameter with the function which is put into a hidden field, and a switch statement checks that field in order to know which field to send the data back to.

It works, but it seems like I should be able to do this with a lot less code, and something that isn't so statically programmed (I don't want to manually update the switch statement when I add new fields to the form). I hope there's a simple answer, I'm new to programming and anything complex I won't understand.

A simplified example of what I've got is this:

<form action="#" name="testForm">
    <input type="text" name="input1" size="20">
    <input type=button value="get data" onClick="populateField(1)"/>
    <br>
    <input type="text" name="input2" size="20">
    <input type=button value="get data" onClick="populateField(2)"/>
    <br>
    <input type="text" name="input3" size="20">
    <input type="button" value="get data" onClick="populateField(3)"/>
    <br>
    <input type="text" name="lineID" size=1 style="display:none"/>
</form>

<script>
    function populateField(input) {
        document.testForm.lineID.value = input;
        var element = document.getElementById("lineID");
        var lineID = element.value;
        switch (lineID) {
            case "1":
                document.testForm.input1.value = "some value";
                break;
            case "2":
                document.testForm.input2.value = "some value";
                break;
            case "3":
                document.testForm.input3.value = "some value";
            //etc
        }
    }
</script>

Instead of a separate case for every "document.testForm.input#.value", how can I use the variable to substitute for the "input#"?

1
  • 2
    Standardize your HTML: use lowercase HTML tags please, and double quote all attribute values. Commented Mar 11, 2013 at 4:45

1 Answer 1

3

Use bracket notation:

document.testForm['input' + lineID].value
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.