Flo Flo - 3 months ago 8
CSS Question

Keeping JQuery CSS settings on failed form submit

On a wordpress I have created I am using a drop down to show 1 of 3 hidden forms via JQuery.

The first problem is when a form is invalid (ie. missing field, bad email ect.) the form resets the page so everything is no longer visible until you have selected that form from the drop down again.

The second is that the form is a plug in so I do not direct access to the submit operation and if I were to go into the plug in files, it would likely be overwritten by update in the near future.

HTML:

<div class="ginput_container ginput_container_select">
<select id="app_pick" class="medium gfield_select">
<option value="">Choose Here</option>
<option value="Greek_Dance">Greek Dance</option>
<option value="Greek_School">Greek School</option>
<option value="Youth_Group">Youth Group</option>
</select></div>


JQUERY:

jQuery(document).ready(function($){

$('#gform_wrapper_3').hide();


$('#app_pick').on('change', function() {
if ( this.value == ''){
$('.f1').css('display', 'none');
$('.f2').css('display', 'none');
$('.f3').css('display', 'none');
}
else if ( this.value == 'Greek_Dance'){
$('.f1').css('display', 'block');
$('.f2').css('display', 'none');
$('.f3').css('display', 'none');
}
else if ( this.value == 'Greek_School'){
$('.f1').css('display', 'none');
$('.f2').css('display', 'block');
$('.f3').css('display', 'none');
}
else if ( this.value == 'Youth_Group'){
$('.f1').css('display', 'none');
$('.f2').css('display', 'none');
$('.f3').css('display', 'block');
}
else {
$('.f1').css('display', 'none');
$('.f2').css('display', 'none');
$('.f3').css('display', 'none');
}

});

});


F1,F2,F3 are the respective forms which are Display: none by default.

My goal is to have the form selected in the drop down stay Display: block; after the submit has occurred.

Answer

I refactored your solution a bit to get rid of the if-else construct:

var form = localStorage.getItem('showForm');
if (form) {
  $('.' + form).show();
  $('#app_pick').val(localStorage.getItem('option'))
}

$('#app_pick').on('change', function() {
  var showForm;

  $('.f1, .f2, .f3').hide();

  switch (this.value) {
    case 'Greek_Dance':
      $('.f1').show();
      showForm = 'f1';
      break;
    case 'Greek_School':
      $('.f2').show();
      showForm = 'f2';
      break;
    case 'Youth_Group':
      $('.f3').show();
      showForm = 'f3';
      break;
  }
  localStorage.setItem('showForm', showForm);
  localStorage.setItem('option', this.value);
});

What I'm doing here is saving the selected value and its accompanying form into the localStorage to use it when the page reloads.


Example