tags:

views:

24

answers:

1

In my form I show/hide certain divs based on the radio button selection by the user. For example:

$('input[name=\'pick_up_point\']').change(function() {
if($($(this)).val() == 'pick_up_airport')
{
    $('#pick_up_airport_div').slideDown();
    $('#start_point_div').hide();
}
});

Now when the form is submitted, and if there is an error the form is redisplayed. The validation is working fine, except of course the divs are back in their original states. How can I retain the show/hide states?

+2  A: 

Onload of the page you could fire the change event for all radio buttons:

$('input[name=\'pick_up_point\']').trigger('change');

This would need to be called after you've defined the change handler.

Pat
But that would run that trigger on first page load also..
GSTAR
Since all your radio buttons would be empty, would this be a problem? I've often used the above approach to persist javascript set states over page loads.
Pat
Well by default the first radio button is always selected. Actually I can put in a PHP condition to check what the POST value of the field was. How can I now do a check in the trigger for that post value?
GSTAR
Ah true. You can't actually check in the trigger since it just invokes your change handler. But what you could do is check in your change handler function for that POST value. Perhaps you could have a hidden input that's only populated when a validation error is present. Then you could just skip your change handler code if it's not set (i.e. it's the initial page load).
Pat
Basically there are three different conditions in my change handler - if($($(this)).val() == 'condition_value') - how can I pass through the condition value to the trigger?
GSTAR
EDIT: I sorted that - I was using $(this)).val() instead of $('input[name=\'pick_up_point\']:checked').val(). Is it possible to use $(this) to refer to the element at all?
GSTAR
Got another slight issue - in my change handler I call a function "clearFields()" which basically clears out the input fields. Now when I post the page the trigger is run and it calls the change handler, which of course runs the clearFields() function. So how can I get around this? I don't want the fields being cleared when the form is re-displayed.
GSTAR