Search code examples
jqueryhideshow

Hide and show form elements when preselected option is loaded


I have this jQuery to show and hide form fields. I start by hiding them

$('#edit-profile-letter-of-introduction-field-sign-off').hide();
$('#edit-profile-letter-of-introduction-field-signatory').hide();
$('#edit-profile-letter-of-introduction-field-position').hide();

And then I have a change event that shows and hides them according to the value of a select field

$('#edit-profile-letter-of-introduction-field-template-und').change(function() {
  switch ($(this).val()) {
   case '1':
   $('#edit-profile-letter-of-introduction-field-sign-off').show();
   $('#edit-profile-letter-of-introduction-field-signatory').hide();
   $('#edit-profile-letter-of-introduction-field-position').hide();
   break;

   etc etc

Works fine. I then save the form. When the form returns, all the fields are hidden again.

What I want to happen is when a form is loaded, and there is already a selection in the select field - or when the select field has a default value - then I want the other form fields hidden or shown but without requiring the change event.

Then I want the change event to work if the user changes the value of the select field.


Solution

  • Please refer below code sample. In below example I am loading input with default value "test" so first case will be executed on load. And then if you change input to "test1" then it will execute second case. Similarly you can add further cases.

    <input type="text" id="demoInput" value="test">
    <lable id="lbl">test</lable>
    <lable id="lbl1">test1</lable>
    <lable id="lbl2">test2</lable>
    
    
    
    $(document).ready(function(){
     var defaultValue = $("#demoInput").val();
     hideShowElements(defaultValue);
      $("#demoInput").change(function(){   
        hideShowElements($(this).val());
      });
    });
    function hideShowElements(defaultValue){
      switch (defaultValue) {
       case 'test':
        $("#lbl").show();
        $("#lbl1").hide();
        $("#lbl2").hide();
       break;
       case "test1":
       $("#lbl").hide()
        $("#lbl1").show();
        $("#lbl2").show();
       break;
       };
     }