简体   繁体   中英

jquery show/hide on user selection and form validation

I have form with an 'Employment Status' section. If the user selects 'Employed' from a drop-down list (#employment_status), then the following jQuery code shows an additional div section (which starts off hidden) with more fields for the user to fill out:

<script type="text/javascript">
var employ = jQuery('#employment_status');
var select = this.value;
employ.change(function() {
    if ($(this).val() == 'Employed' ){
        $('#employed').show(2000, 'easeOutExpo');
    } else $('#employed').hide(2000, 'easeOutExpo');
});
</script>

This works if the user manually selects 'Employed'. However if the user selects 'Employed', submits the form, and there are validation errors which show up on the form (using in my case PHP which re-inserts all the values in the form and makes 'Employed' the 'selected' option in the dropdown), the 'Employed' section will come back closed . The only way to show the div section is to fiddle around with another value and choose 'Employed' again manually.

Is a solution to making the form come back with this div open if the 'selected' value is Employed.

One possible solution is to trigger the change event manually after the handler is registered

var employ = jQuery('#employment_status');
var select = this.value;
employ.change(function () {
    if ($(this).val() == 'Employed') {
        $('#employed').show(2000, 'easeOutExpo');
    } else {
        $('#employed').hide(2000, 'easeOutExpo')
    };
}).change(); //trigger the change event manuall to set the initial state

try this

var employ = jQuery('#employment_status');

// check when form load
if ($('#employment_status').val() == 'Employed' )
{
        $('#employed').show(2000, 'easeOutExpo');
} 
else
{
        $('#employed').hide(2000, 'easeOutExpo');
}

employ.change(function() {
    if ($(this).val() == 'Employed' ){
        $('#employed').show(2000, 'easeOutExpo');
    } else $('#employed').hide(2000, 'easeOutExpo');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM