Dave Walker Dave Walker - 3 days ago 4
jQuery Question

Accessing and Validating Multiple select boxes in a table with Jquery

I have two columns in a Table, and in each column is a Select dropdown. The second dropdown is either enabled or disabled dependant on the value of the first.

This works find for the first row, but when I add multiple rows (actually done dynamically within a program) the "id" are the same and the validation for enable and disable fails to work - I suspect because of the same names.

Any ideas how I can best get this to work with multiple rows?

Example of where I am so far - https://jsfiddle.net/dave_pace/L8naac5u/

<table id="example" >
<tr>
<th>Site</th>
<th>Location</th>
</tr>

<tr>
<td>
<select name="site" id="site">
<option value="Local" selected="">Local</option>
<option value="Remote">Remote</option>
</select>
</td>
<td>
<select name="remotesite" id="remotesite" disabled>
<option value="&quot;"></option>
<option value="Acme Ltd 0001">Acme Ltd 0001</option>
<option value="Acme Ltd 0002">Acme Ltd 0002</option>
<option value="Acme Ltd 0003">Acme Ltd 0003</option>
</select>
</td>
</tr>
<tr>
<td>
<select name="site" id="site">
<option value="Local" selected="">Local</option>
<option value="Remote">Remote</option>
</select>
</td>

<td>
<select name="remotesite" id="remotesite" disabled>
<option value="&quot;"></option>
<option value="Acme Ltd 0001">Acme Ltd 0001</option>
<option value="Acme Ltd 0002">Acme Ltd 0002</option>
<option value="Acme Ltd 0003">Acme Ltd 0003</option>
</select>
</td>
</tr>
<tr>
<td>
<select name="site" id="site">
<option value="Local" selected="">Local</option>
<option value="Remote">Remote</option>
</select>
</td>

<td>
<select name="remotesite" id="remotesite" disabled>
<option value="&quot;"></option>
<option value="Acme Ltd 0001">Acme Ltd 0001</option>
<option value="Acme Ltd 0002">Acme Ltd 0002</option>
<option value="Acme Ltd 0003">Acme Ltd 0003</option>
</select>
</td>
</tr>

</table>

$(document).ready(function(){
function updateTable() {

// alert('hi');

// alert($(this).val());

// alert($(this).text());

if ($(this).val() == "Remote") {
document.getElementById('remotesite').disabled=false;
}
else {
document.getElementById('remotesite').disabled=true;
}

}

$("#site").change(updateTable);

});


Many thanks
Dave

Answer

Warning: You should not declare multiple id's with the same value, for that you can use classes. The id must be unique, unlike classes that can be multiple with the same value.

Solution: Remove your id's from select tags and replace this script tag with yours.

<script type="text/javascript">
$("select[name='site']").change(function(){
    var _this = $(this);
    _this.parent().siblings().children("select[name='remotesite']").attr('disabled', false)
});
</script>