Pergunta

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?

Foi útil?

Solução

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

Outras dicas

Try adding this inside doc.ready:

if ($('input:radio[name="accountType"]').val() == 'typeA') {
  $( "#additionalQuestion" ).show();
}

As @Poornima mentioned in a comment, you can run the check both when the radio button is selected and when the page loads.

$(document).ready(function() {

    function checkForAdditionalQuestion() {
        if ($(this).val() == 'typeA'){
            //show the hidden layer
            $( "#additionalQuestion" ).show("slow");
        }
        if ($(this).val() == 'typeB'){
            //show the hidden layer
            $( "#additionalQuestion" ).hide("slow");
        }
    }

    checkForAdditionalQuestion();

    $('input:radio[name="accountType"]').change(function() {
        checkForAdditionalQuestion();
    });
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top