I have a collection of divs that contains either images or checkboxes. My ultimate goal is for the onclick event on the checkbox to also check all previous checkboxes.
Here is my layout (dynamically created, so id # can change based on page load data):
<div id="Main1">
<div id="Secondary1">
<div id="div1">
<img id="section1" src="image1" alt="" />
<span>Div 1 text</span>
</div>
<div id="div2">
<img id="section2" src="image2" alt="" />
<span>Div 2 text</span>
</div>
<div id="div3">
<input type="checkbox" id="section3">
Div 3 text
</input>
</div>
<div id="div4">
<input type="checkbox" id="section4">
Div 4 text
</input>
</div>
<div id="div5">
<input type="checkbox" id="section5">
Div 5 text
</input>
</div>
<div id="div6">
<input type="checkbox" id="section6">
Div 6 text
</input>
</div>
</div>
</div>
I want to be able to check section5 and automatically check previous checkboxes.
The code I used that produces sporadic results is given below:
$('input[id^=section]').click(function() {
if($(this).attr('checked')) {
var slide = $(this).attr('id').replace('section', '');
$(this).replaceWith('<img src="images/ajax-loader.gif" id="loader" alt="" />');
$.ajax({
type: 'POST',
url: 'URL to AJAX page',
data: '{ data for ajax call }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function() {
$('#loader').parents('div[id^=Secondary]').children('div[id^=section]').each(function() {
if($(this).children('input[id^=section]').attr('id') != undefined) {
if($(this).children('input[id^=section]').attr('id').replace('section', '') < slide) {
$(this).children('input[id^=section]').replaceWith('<img src="images/checkmark.gif" alt="" />');
}
}
});
},
error: function() {
}
});
}
});
It seems to me that I am doing this inefficiently, I have tried .prev()and .prevAll(), but to no avail. However, I could use them incorrectly. Any help is appreciated.