For a loop using jquery
What is the correct way to use jquery for loop? TQ in advance.
<script type="text/javascript">
$(document).ready(function() {
for(var $i=1; $i<=10; $i++){
$('#TTID[$i]').change(function() {
if($(this).val() == "601" || $(this).val() == "9999")
{
$('#trainGroup[$i]').prop('disabled', true);
$('#trainID[$i]').prop('disabled', true);
}
else
{
$('#trainGroup[$i]').prop('disabled', false);
$('#trainID[$i]').prop('disabled', false);
}
}});
});
</script>
This is the HTML for TTID and trainGroup. When the user selects the value "601" or "9990", the dropdown list for trainGroup will be disabled.
<td>Action</td>
<td><select name = "TTID<?php echo $i; ?>" id="TTID<?php echo $i; ?>" style="width:250px" onchange="otherAction(this.value)">
<option value="O"></option>
<option value="600">Classroom Training</option>
<option value="601">Coaches and Mentoring by IM</option>
<option value="602">On Job Training</option>
<option value="9999">Others</option>
</select></td>
<td>Types Training in ILSAS</td>
<td><select name = "trainGroup<?php echo $i; ?>" id="trainGroup<?php echo $i; ?>" style="width:250px" onchange="otherIlsas(this.value)">
<option value="O"></option>
<option value="700">Power Engineering & Energy Training</option>
<option value="701">Management Training</option>
<option value="702">IT & Corporate System Training</option>
<option value="703">Business Operation Tools Certification</option>
<option value="9999">Others</option>
</select></td>
Below is the trainID code. I have retrieved data from the database for this dropdown.
<td>List of Training in ILSAS</td>
<td><?php
$u="SELECT trainID, trainText FROM tbltraininglist order by traintext asc";
$q=mysql_query($u);
echo "<select name = 'trainID<?php echo $i; ?>' id='trainID<?php echo $i; ?>' style='width:250px' )'>";
echo "<option value ='null'></option>";
while ($m = mysql_fetch_array($q)) {
?>
<option value="<?php echo $m['trainID']; ?>"><?php echo $m['trainText']; ?> </option>
<?php
}
?>
</select></td>
source to share
Here is your for loop with all the issues fixed
An explanation of your errors follows the code
$(document).ready(function() {
for (var $i = 1; $i <= 10; $i++) {
(function(TTID, trainGroup, trainID) {
$(TTID).change(function() {
if ($(this).val() == "601" || $(this).val() == "9999") {
$(trainGroup).prop('disabled', true);
$(trainID).prop('disabled', true);
} else {
$(trainGroup).prop('disabled', false);
$(trainID).prop('disabled', false);
}
});
}('#TTID[' + $i + ']', '#trainGroup[' + $i + ']', '#trainID[' + $i + ']'));
}
});
1) you had things like $('#TTID[$i]')
- where $ i was var in a for loop which doesn't work in javascript you would need $('#TTID[' + $i + ']')
- however
2) $ i will be 11 for every .change function, because that is the value after the loop has finished and .change will only be called after the loop has finished, so I wrapped the .exchange stuff in IIEF and copy the $ i your code might have for once
source to share