Keeping element hidden on form reload (jQuery)

I have a form that needs to have certain elements hidden depending on which option is selected in a select list.

It works fine, but for this app, the form remains visible after it’s been submitted (so the user can fine-tune search criteria), and when the page re-loads the hidden items become visible again.

This is the jQuery code I’m using:


$(document).ready(function() {
   $("#widget_type").change(function() {
      if($(this).find("option:selected").val() == "combobox") {
         $(".formats").slideUp("fast");
      }
   });
}

Is there a way to embellish it to keep the hidden item hidden when the form is reloaded?

When the page reloads does the form keep the same selected options and such or do you reset them? If they are kept in the same state then in your DOM ready function simply check the fields you need to and if the value matches the required option:selected state hide the element again.

I do keep the options selected when the form reloads, but it seems like my jQuery is set to trigger when the select item is changed (change(function()), and not set to read it when it’s loaded. It seems like I’d have to have something like an onLoad, no? Sorry, I’m quite the beginner when it comes to jQuery!

That is why I said the following in my previous post

…in your DOM ready function simply check the fields you need to and if the value matches the required option:selected state hide the element again

Basically when the page loads in your jQuery DOM ready function you simply need to check the selected value of the option list using the same code, see the below for an example:

function checkWidgetType() {
    if ($('option:selected', this).val() === 'combobox') {
        $('.formats').slideUp('fast');
    }
}

$(function() {
    var $widgetType = $('#widget_type');
    
    // Check the value of the widget type select box
    checkWidgetType.call($widgetType[0]);
    
    // Bind an "onchange" event ot the select box
    $widgetType.on('change', checkWidgetType);
});