I am using jQuery selector to hide and unhide some dynamically generated HTML cells. However, it seems like I did not choose the right selector. So, I appreciate if you could give me some suggestions.
The webpage:
- first ask users to select the number of applications
- based on users selection, generate two input fields “Application timing”, and “Application Date” for each application.
- There are two options in the “Application timing”. If the user chooses “Default”, the “Application Date” will disappear.
Problem:
When there are more than three applications, only the last “Application Date” will disappear, not matter where the selection is made. I think it is because I did not use the right selector.
HTML CODE
<table class="table">
<tr>
<th>
<label for="id_NOA">Number of applications:</label>
</th>
<td>
<select id="id_NOA" class="valid" name="NOA">
<option selected="selected" value="">Choose</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
</tr>
</table>
JavaScript
$(document).ready(function() {
$('#id_NOA').change(function() {
var total = $(this).val();
$('.app_timing').remove();
$('.app_dates').remove();
for (var i = 1; i <= total; i++) {
$('<tr class="app_timing"><th><label for="id_Apt' + i + '">Application timing ' + i + ':</label></th><td><select name="Apt' + i + '" id="id_Apt' + i + '"><option value="" selected="selected">Select an application timing</option><option value="1">Default</option><option value="2">Enter your own</option></select></td></tr>').appendTo('.table')
$('<tr class="app_dates"><th><label for="id_Date_apt">Application Date ' + i + ':</label></th><td><input readonly="readonly" type="text" name="Date_apt' + i + '" value="MM/DD" id="id_Date_apt' + i + '"/><td></tr>').appendTo('.table')
$('.app_timing:last').find('select').bind('change', function() {
if ($(this).val() == '1') {
$('.app_dates:last').hide()
//$('#id_Date_apt' + i).hide() //I tried to use ID selector, but it does not work
}
})
}
})
})
The above line is within the
changehandler and is not executed until the handler fires. At the time it fires, this will get the last element, which causes the behavior you observed. You can use the following:Note that this is based on your current html. A change would require this to change. It simply hides the next row in the table.
EDIT:
While the above answers the question, an overall better approach would be to use event delegation. This will allow you to attach a single handler rather than creating new handlers every time the dropdown is changed. (Note that I added a class to each select to simplify the selector)
http://jsfiddle.net/JDFcn/11/