Reputation: 37
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#"
?
Upvotes: 0
Views: 400
Reputation: 191749
Use bracket notation:
document.testForm['input' + lineID].value
Upvotes: 3