Reputation: 6997
Am trying to build a generic way of managing hiding and showing certain fields based on checkboxes. In my project, it is common that some forms might contain a check field whereby if the checkbox is ticked it will be associated with other fields and they will appear or hide based on the checkbox.
am a newbie with javascripting and am hoping someone will help me in staying in the right path here. In my django form, I used the data attribute to indicate a flag for the checkbox and data field to indicate what fields will be effected as following:
class PackageForm(forms.ModelForm):
'''
PackageForm
'''
class Meta:
model = Package
widgets = {
'recurring_flag' : CheckboxInput(attrs={'data-collapse-flag' : 'True'}),
'recurring_type' : Select(attrs={'data-collapse-id' : 'recurring_flag'}),
'recurring_period' : TextInput(attrs={'data-collapse-id' : 'recurring_flag'}),
}
Off course, do to my limited knowledge in jquery i was able to write it statically as following
$(document).ready(function() {
$('input[data-collapse-flag]').click(function() {
if ($(this).is(':checked')) {
$("label[for='id_recurring_type']").show();
$('#id_recurring_type').show();
$("label[for='id_recurring_period']").show();
$('#id_recurring_period').show();
}else{
$('#id_recurring_type').hide();
$("label[for='id_recurring_type']").hide();
$('#id_recurring_period').hide();
$("label[for='id_recurring_period']").hide();
}
});
});
but, i really want to create a single javascript file that would read the data-collapse-flag and build an action to loop through any field with data-collapge-id to apply the action too. so, I can use the script generically across all my forms wherever this scenario is required.
If anyone can advise me on how to build such a thing or point me to the method, it is very much appreciated.
regards,
Upvotes: 0
Views: 1563
Reputation: 76
Just as some conceptual support: what you want is to loop through the descendants of a given element and based on a switch, add behavior, right?
You want to try something like:
like:
$(document).ready(function() {
$('.collapse-stack').each(function(){
//this = current collapse stack
$(this).click(function() {
if ( $(this).is(':checked') ) {
$(".collapse-label, .collapse-list").each(function(){
//this = current collapse-label
$(this).show();
});
}else{
$(".collapse-label, .collapse-list").each(function(){
//this = current collapse-label
$(this).hide();
});
}
});
})
});
or somesuch. Play around with that "each" function.
Upvotes: 1