I have a form which has follow-up questions that should be shown only shown if they answer a particular other question a certain way. The way I have it set up right now works great if I start out with a blank form. However, when the user comes back to edit the form and its loading whether the checkboxes are pre-checked from the database (via php), my design is breaking down.
So I need some advice or suggestions on how to best restructure my jquery code so that it will show and hide the correct elements when the form loads.
Right now, I have a number of .change() functions for checkboxes or option buttons that cause other (or multiple) elements to hide and/or show, such as the following:
$("#elt_prev_divorced").change(function () {
if ($(this).is(":checked")) {
$("#questions_divorced").show("slow");
} else {
$("#questions_divorced").hide("slow");
}
});
$("input").change(function () {
var selected_item = $(this).attr('id');
switch (selected_item) {
case "elt_married":
$("#elt_inrel_yes").attr('checked', true);
$("#elt_reldes_married").attr('checked', true);
$("#li_spouse_or_partner").show("slow");
$("#li_marriages").show("slow");
break;
case ...
}
And then I have a CSS class called “initially_hidden” that is set for all items that shouldn’t be shown when the form loads if the form is blank. In my document ready function, I hide everything with that CSS tag.
(function($) {
$(".initially_hidden").hide();
})(jQuery);
After I hide those elements, however, I now need to do the equivalent of all of those .change() functions to handle the form being loaded with existing data. I know I could copy and paste my change functions into document ready to do this, but aside from being certainly horrific style were I do that, I would much prefer to minimize duplicate code. So how could I do this best/efficiently? I am somewhat new to JQuery, so I’m not sure what direction to take here. Thank you!
Firstly in your css
.initially_hiddencan havedisplay:noneset in the stylesheet or the in-page style. jQuery will setdisplay:blockor whatever in the inline style. So I don’t see the sense of callinghide()on your elements with the classinitially_hidden.What I would do is handle this on the server side and set
initially_hiddenon all elements that should not be displayed and let my css hide those elements.This way, all the elements are on the form that should be displayed and all that should not be displayed are hidden. If you have a checkbox checking which will make other elements visible, I would suggest you do 1 of 2 things.
Traverse the dom relative to your checkbox to determine which element should be displayed, hence no need to hardcode an id. This fiddle has an example of something like this.
Add a custom attribute to your checkbox which contains the id for the div/element you want to display:
HTML
jQuery
Hope this helps and makes sense.