I have a form where, if a radio button is selected, the user is prompted with an additional text field. I'm using the following jQuery to accomplish this:
$(document).ready(function(){
$('input:radio[name="accountType"]').change(function() {
if ($(this).val() == 'typeA'){
//show the hidden layer
$( "#additionalQuestion" ).show("slow");
}
if ($(this).val() == 'typeB'){
//show the hidden layer
$( "#additionalQuestion" ).hide("slow");
}
});
});
Everything works perfectly unless the user's responses fail my PHP form validation, in which case the form is redisplayed (with the user's responses injected via PHP). At this point, the #additionalQuestion layer is no longer visible, even though the appropriate radio button is selected. How can I ensure that the #additionalQuestion layer remains visible in this case?
In the same place you're injecting form elements, inject a JavaScript variable that your $(document).ready()
can pick up
In PHP
if ($form_failed)
echo '<script>var showAdditionalQuestion = 1;</script>';
Then in JS
$(document).ready(function(){
if (showAdditionalQuestion)
$('#showAdditionalQuestion').show();
});
(Or just inject the code so show the section directly)
This is probably more flexible and robust than just checking if the checkbox is checked on load (what if a form input is set but you don't want to show that section on load?), but that's an alternative