I have a table that contains 2 columns. The first one has a dropdown that needs to be selected in order to display its value in the second column. The problem is that only the first row of the table is being updated. When selecting the second dropdown, the first row is being updated. I am not a javascript developer and I am searching how to address this problem.
Here is part of the code:
function updateinput(e) {
var selectedOption = e.options[e.selectedIndex];
document.getElementById('viewvalue').value = selectedOption.getAttribute('data-name');
}
<tr>
<td>
<select onchange="updateinput(this)">
<option data-name="">Select</option>
<option data-name="value 1">test 1</option>
<option data-name="value 2">test 2</option>
</select>
<td><input type="text" id="viewvalue" name="viewvalue"></td>
<br>
<td>
<select onchange="updateinput(this)">
<option data-name="">Select</option>
<option data-name="value 1">test 1</option>
<option data-name="value 2">test 2</option>
</select>
<td><input type="text" id="viewvalue" name="viewvalue"></td>
</tr>
You have to keep reference to the select field. Since you already used the data-attribute, I did the same in the example.
The attached data-select-index
allows you to reference the id
of the corresponding input-field. E.g. select-tag data-select-index="num1"
references input-tag id="view-num1"
and so on
function updateinput(e) {
var selectedOption = e.options[e.selectedIndex];
document.getElementById('view-' + e.getAttribute('data-select-index')).value = selectedOption.getAttribute('data-name');
}
<tr>
<td>
<select data-select-index="num1" onchange="updateinput(this)">
<option data-name="">Select</option>
<option data-name="value 1">test 1</option>
<option data-name="value 2">test 2</option>
</select>
<td><input type="text" id="view-num1" name="viewvalue"></td>
<br>
<td>
<select data-select-index="num2" onchange="updateinput(this)">
<option data-name="">Select</option>
<option data-name="value 1">test 1</option>
<option data-name="value 2">test 2</option>
</select>
<td><input type="text" id="view-num2" name="viewvalue"></td>
</tr>