Jump to content

Form Block: Conditional Logic For "Other, Please Specify."

Go to solution Solved by jpeter,

Recommended Posts

Site URL: https://www.mmclassy.com/contact-us

Hello wonderful people!

I am currently trying to apply conditional logic to the "Event Type" select field on my form. I'd like the "Other, please specify" text field to be shown only if the "Other" option is selected. I assume this is possible because I've seen it done with the checkbox field in a video from 2019. Unfortunately I was not able to adapt this code to the select field.

Does anyone know how to implement this feature?

Edited by shiDMV
Link to comment

@shiDMV The javascript code below should work for you. 

Javascript

(function(){

  // The value of the "id" HTML attribute of the parent HTML element
  var PARENT_ID = 'select-61719a1c-6980-4b16-b86c-5a7ccff1e8e5-field';

  // The value which will determine the visibility of the DEPENDENT_ID element
  var PARENT_VALUE = 'Other';

  // The value of the "id" HTML attribute of the child HTML element.
  // This field will hide/show depending on the PARENT_VALUE
  var DEPENDENT_ID = 'text-48e31159-ed89-4857-9813-092474be4290';


  /*********************************************************************
   * DO NOT ALTER BELOW THIS LINE UNLESS YOU KNOW WHAT YOU'RE DOING
   *********************************************************************/

  // Initialize after the page has been loaded
  if (document.readyState === 'complete') {
    init();
  } else {
    document.addEventListener("DOMContentLoaded", init, false);
  }

  function init() {
    // Load jQuery if not loaded
    if(!window.jQuery) { return loadJquery(init) }

    // Assign jQuery to a variable
    var $ = jQuery;

    // Get the parent element 
    var $parentField = $('#' + PARENT_ID);

    // Get the dependent element
    var $dependentField = $('#'+ DEPENDENT_ID);

    // Hide the text field on page load
    $dependentField.hide();
  
    // Show or hide the dependent field based on the PARENT_VALUE
    $parentField.on('change', function(evt){
      if(evt.currentTarget.value == PARENT_VALUE ) {
        $dependentField.slideDown();
      } else {
        $dependentField.slideUp();
      }
    });
  }

  function loadJquery(init) {
    var s = document.createElement('script');
    s.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
    s.integrity = 'sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=';
    s.crossorigin = 'anonymous';
    s.onload = init;
    document.body.appendChild(s);
  };
})()

Make sure to place this between <script> tags. For example:

<script>
  // Place JS Code Here
</script>

 

Edited by jpeter
Uploading video example

Full stack developer who loves helping people out with anything web related. If you'd like to support me, buy me a coffee!

Link to comment
  • 11 months later...
  • 3 weeks later...

@ratkaj

The following JS should work for your case. Since you have multiple fields that need to be hidden, I updated the DEPENDENT_IDS variable to allow for multiple field id's to be added. 

(function(){

  // The value of the "id" HTML attribute of the parent HTML element
  var PARENT_ID = 'radio-34cca7d9-f70c-4cd4-8493-81bbed9965e2';

  // The value which will determine the visibility of the DEPENDENT_ID element
  var PARENT_VALUE = 'No';

  // The value of the "id" HTML attribute of the child HTML element.
  // This field will hide/show depending on the PARENT_VALUE
  var DEPENDENT_IDS = [
      'section-ceb19c7b-270b-4063-b795-d85f0025ed12',
      'time-b4fba215-e6fc-4f4a-85a6-d5275df985d7',
      'time-45e67131-51ca-4f9a-b249-d0ee2fa30076'
  ];


  /*********************************************************************
   * DO NOT ALTER BELOW THIS LINE UNLESS YOU KNOW WHAT YOU'RE DOING
   *********************************************************************/

  // Initialize after the page has been loaded
  if (document.readyState === 'complete') {
    init();
  } else {
    document.addEventListener("DOMContentLoaded", init, false);
  }

  function init() {
    // Load jQuery if not loaded
    if(!window.jQuery) { return loadJquery(init) }

    // Assign jQuery to a variable
    var $ = jQuery;

    // Get the parent element 
    var $parentField = $('#' + PARENT_ID);
	
    // Create ID CSS selectors based on the DEPENDENT_ID.
    var ids = DEPENDENT_IDS.map(id => '#' + id);

    ids.forEach(id => {
      // Get the dependent element
      var $dependentField = $(id);

      // Hide the text field on page load
      $dependentField.hide();
    });
  
    // Show or hide the dependent field based on the PARENT_VALUE
    $parentField.on('change', function(evt){
      if(evt.target.value == PARENT_VALUE ) {
        $(ids.join(',')).slideDown();
      } else {
        $(ids.join(',')).slideUp();
      }
    });
  }

  function loadJquery(init) {
    var s = document.createElement('script');
    s.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
    s.integrity = 'sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=';
    s.crossorigin = 'anonymous';
    s.onload = init;
    document.body.appendChild(s);
  };
})()

 

Edited by jpeter

Full stack developer who loves helping people out with anything web related. If you'd like to support me, buy me a coffee!

Link to comment
  • 3 weeks later...

Hi there, 

For some reason, my conditional logic coding randomly stopped working a couple of weeks ago.
I am attempting to do the same idea as this thread:
Within the How did you hear about us? field, if a user selects the "Referral" radio button, a Name (first and last), should appear. If a user selects "Other", then a field "Specify" a text field appears. 
Again this was working up until a month ago or so (the client believes). 
I've attempted a couple of different fixes and code changes, and I've successfully hidden the fields, but now cannot get the conditional logic to fire.
Hoping for some help from the Squarespace crew!

Webpage: https://www.leanagilesensei.com/contact

In the Code Injection section of the site, I have:

In HEADER:
<style>
#name-yui_3_17_2_1_1600810502501_7975,
#text-yui_3_17_2_1_1603146836044_49833 {
  display: none;
}
</style>

 

FOOTER:

<script 
        (function(){

  // The value of the "id" HTML attribute of the parent HTML element
  var PARENT_ID = 'radio-yui_3_17_2_1_1603146836044_50638';

  // The value which will determine the visibility of the DEPENDENT_ID element
  var PARENT_VALUE = ['Referral', 'Other'];

  // The value of the "id" HTML attribute of the child HTML element.
  // This field will hide/show depending on the PARENT_VALUE
  var DEPENDENT_IDS = [
      'name-yui_3_17_2_1_1600810502501_7975',
      'text-yui_3_17_2_1_1603146836044_49833'
  ];


  /*********************************************************************
   * DO NOT ALTER BELOW THIS LINE UNLESS YOU KNOW WHAT YOU'RE DOING
   *********************************************************************/

  // Initialize after the page has been loaded
  if (document.readyState === 'complete') {
    init();
  } else {
    document.addEventListener("DOMContentLoaded", init, false);
  }

  function init() {
    // Load jQuery if not loaded
    if(!window.jQuery) { return loadJquery(init) }

    // Assign jQuery to a variable
    var $ = jQuery;

    // Get the parent element 
    var $parentField = $('#' + PARENT_ID);
    
    // Create ID CSS selectors based on the DEPENDENT_ID.
    var ids = DEPENDENT_IDS.map(id => '#' + id);

    ids.forEach(id => {
      // Get the dependent element
      var $dependentField = $(id);

      // Hide the text field on page load
      $dependentField.hide();
    });
  
    // Show or hide the dependent field based on the PARENT_VALUE
    $parentField.on('change', function(evt){
      if(PARENT_VALUE.includes(evt.target.value)) {
        $(ids.join(',')).slideDown();
      } else {
        $(ids.join(',')).slideUp();
      }
    });
  }

  function loadJquery(init) {
    var s = document.createElement('script');
    s.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
    s.integrity = 'sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=';
    s.crossorigin = 'anonymous';
    s.onload = init;
    document.body.appendChild(s);
  };
})();

</script>

Edited by JamesonW
Wrong parent id
Link to comment
53 minutes ago, JamesonW said:

For some reason, my conditional logic coding randomly stopped working a couple of weeks ago.

It wasn't random 🙂. Squarespace replaced the Form Block in May 2023 with a newer version. This update caused a number of changes, including different classes, element types, and a different technology. As a result, you'll need to review your code and re-write some of it.

There's more information in my earlier post in another thread:

Did this help? Please give feedback by clicking an icon below  ⬇️

Me: I'm Paul, a SQSP user for >18 yrs & Circle Leader since 2017. I value honesty, transparency, diversity and good design ♥.
Work: Founder of SF.DIGITAL. We provide high quality original extensions to supercharge your Squarespace website. 
Content: Views and opinions are my own. Links in my posts may refer to my own SF.DIGITAL products or may be affiliate links.
Forum advice is completely free. You can thank me by selecting a feedback emoji. Buying a coffee is generous but optional.

Would you like your customers to be able to mark their favourite products in your Squarespace store?

Link to comment

@JamesonW

The following JS will work for your case. Needed to update the code to look at the "name" HTML attribute for the parent field, rather than the "id" attribute. 

(function(){

    // The value of the "name" HTML attribute of the parent HTML element
    var PARENT_NAME = 'radio-yui_3_17_2_1_1603146836044_50638-field';
  
    // The value which will determine the visibility of the DEPENDENT_ID element
    var PARENT_VALUE = ['Referral', 'Other'];
  
    // The value of the "id" HTML attribute of the child HTML element.
    // This field will hide/show depending on the PARENT_VALUE
    var DEPENDENT_IDS = [
        'name-yui_3_17_2_1_1600810502501_7975',
        'text-yui_3_17_2_1_1603146836044_49833'
    ];


    // The amount of time in milleseconds to intialize the code. 
    // This allows other code to run before our code is initialized.
    var DELAY = 500;
  
  
    /*********************************************************************
     * DO NOT ALTER BELOW THIS LINE UNLESS YOU KNOW WHAT YOU'RE DOING
     *********************************************************************/
  
    // Initialize after the page has been loaded
    if (document.readyState === 'complete') {
        setTimeout(init, DELAY)
      init();
    } else {
      document.addEventListener("DOMContentLoaded", function(){
        setTimeout(init, DELAY);
      }, false);
    }
  
    function init() {
      // Load jQuery if not loaded
      if(!window.jQuery) { return loadJquery(init) }
  
      // Assign jQuery to a variable
      var $ = jQuery;
  
      // Get the parent element 
      var $parentField = $('[name="' + PARENT_NAME + '"]');
  
      
      // Create ID CSS selectors based on the DEPENDENT_ID.
      var ids = DEPENDENT_IDS.map(id => '#' + id);
  
      ids.forEach(id => {
        // Get the dependent element
        var $dependentField = $(id);
  
        // Hide the text field on page load
        $dependentField.hide();
      });
    
      // Show or hide the dependent field based on the PARENT_VALUE
      $parentField.on('change', function(evt){
        if(PARENT_VALUE.includes(evt.target.value)) {
          $(ids.join(',')).slideDown();
        } else {
          $(ids.join(',')).slideUp();
        }
      });
    }
  
    function loadJquery(init) {
      var s = document.createElement('script');
      s.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
      s.onload = init;
      document.body.appendChild(s);
    };
  })();

 

Edited by jpeter
Add "DELAY" variable to delay code initialization

Full stack developer who loves helping people out with anything web related. If you'd like to support me, buy me a coffee!

Link to comment
16 hours ago, paul2009 said:

It wasn't random 🙂. Squarespace replaced the Form Block in May 2023 with a newer version. This update caused a number of changes, including different classes, element types, and a different technology. As a result, you'll need to review your code and re-write some of it.

There's more information in my earlier post in another thread:

Did this help? Please give feedback by clicking an icon below  ⬇️

Thank you so much! I hoped/thought as much

Link to comment
13 hours ago, jpeter said:

@JamesonW

The following JS will work for your case. Needed to update the code to look at the "name" HTML attribute for the parent field, rather than the "id" attribute. 

(function(){

  // The value of the "name" HTML attribute of the parent HTML element
  var PARENT_NAME = 'radio-yui_3_17_2_1_1603146836044_50638-field';

  // The value which will determine the visibility of the DEPENDENT_ID element
  var PARENT_VALUE = ['Referral', 'Other'];

  // The value of the "id" HTML attribute of the child HTML element.
  // This field will hide/show depending on the PARENT_VALUE
  var DEPENDENT_IDS = [
      'name-yui_3_17_2_1_1600810502501_7975',
      'text-yui_3_17_2_1_1603146836044_49833'
  ];


  /*********************************************************************
   * DO NOT ALTER BELOW THIS LINE UNLESS YOU KNOW WHAT YOU'RE DOING
   *********************************************************************/

  // Initialize after the page has been loaded
  if (document.readyState === 'complete') {
    init();
  } else {
    document.addEventListener("DOMContentLoaded", init, false);
  }

  function init() {
    // Load jQuery if not loaded
    if(!window.jQuery) { return loadJquery(init) }

    // Assign jQuery to a variable
    var $ = jQuery;

    // Get the parent element 
    var $parentField = $('[name="' + PARENT_NAME + '"]');

    
    // Create ID CSS selectors based on the DEPENDENT_ID.
    var ids = DEPENDENT_IDS.map(id => '#' + id);

    ids.forEach(id => {
      // Get the dependent element
      var $dependentField = $(id);

      // Hide the text field on page load
      $dependentField.hide();
    });
  
    // Show or hide the dependent field based on the PARENT_VALUE
    $parentField.on('change', function(evt){
      if(PARENT_VALUE.includes(evt.target.value)) {
        $(ids.join(',')).slideDown();
      } else {
        $(ids.join(',')).slideUp();
      }
    });
  }

  function loadJquery(init) {
    var s = document.createElement('script');
    s.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
    s.integrity = 'sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=';
    s.crossorigin = 'anonymous';
    s.onload = init;
    document.body.appendChild(s);
  };
})();

 

Thank you, but still no luck.
I replaced the code in the FOOTER section within the Code Injection section of the site and nothing changed 😞

Link to comment
20 hours ago, JamesonW said:

Thank you, but still no luck.
I replaced the code in the FOOTER section within the Code Injection section of the site and nothing changed 😞

@JamesonW Updated the code above to remove a couple of lines from the loadJquery function. Hopefully that fixes the issue. 

Full stack developer who loves helping people out with anything web related. If you'd like to support me, buy me a coffee!

Link to comment
2 hours ago, jpeter said:

@JamesonW Updated the code above to remove a couple of lines from the loadJquery function. Hopefully that fixes the issue. 

Thanks @jpeter, I really appreciate all this help! Looks like that edit did have a positive effect! The form logic works! But for some reason, I'm only seeing it work through my Backend account.
As in, at this time it doesn't seem to appear to function on the live version of the site? I tried clearing my cache but no luck. I also tested on Mobile and no luck. 
But we're getting somewhere! See video below
https://www.leanagilesensei.com/contact

Link to comment
  • 2 weeks later...
On 6/26/2023 at 2:53 AM, JamesonW said:

Thanks @jpeter, I really appreciate all this help! Looks like that edit did have a positive effect! The form logic works! But for some reason, I'm only seeing it work through my Backend account.
As in, at this time it doesn't seem to appear to function on the live version of the site? I tried clearing my cache but no luck. I also tested on Mobile and no luck. 
But we're getting somewhere! See video below
https://www.leanagilesensei.com/contact

Form Logic Test.mov

@JamesonW Sorry for the delay, I've updated the code above to add a DELAY variable to delay the code's initialization function by 500 milliseconds. My guess is that the code was running too early. 

Full stack developer who loves helping people out with anything web related. If you'd like to support me, buy me a coffee!

Link to comment
  • 1 month later...

@Dovely2023 I was able use the code from this comment and updating the variables defined in that code to:
 

var PARENT_NAME = 'radio-b9c27b14-d706-4412-a2ab-f55f3b91aabe-field';
var PARENT_VALUE = ['Other'];
var DEPENDENT_IDS = [
    'textarea-yui_3_17_2_1_1565803470281_5944',
];


I pulled the ID for the "Describe your project scope" field's <div> container as an example. If it still doesn't work, try increasing the value of the DELAY variable in the JS code. You may need to play around with that. 

 

Edited by jpeter

Full stack developer who loves helping people out with anything web related. If you'd like to support me, buy me a coffee!

Link to comment
22 hours ago, jpeter said:

@Dovely2023 I was able use the code from this comment and updating the variables defined in that code to:
 

var PARENT_NAME = 'radio-b9c27b14-d706-4412-a2ab-f55f3b91aabe-field';
var PARENT_VALUE = ['Other'];
var DEPENDENT_IDS = [
    'textarea-yui_3_17_2_1_1565803470281_5944',
];


I pulled the ID for the "Describe your project scope" field's <div> container as an example. If it still doesn't work, try increasing the value of the DELAY variable in the JS code. You may need to play around with that. 

 

 

That worked perfectly. Thank you so much for your help @jpeter!

Link to comment
  • 1 month later...
On 7/4/2023 at 5:32 PM, jpeter said:

@JamesonW Sorry for the delay, I've updated the code above to add a DELAY variable to delay the code's initialization function by 500 milliseconds. My guess is that the code was running too early. 

Hi @jpeter! I'm trying to apply this code to my client site. I'd love to have my 3 primary drop downs showing service categories, and then depending on which category is chosen, a drop down would appear where the user can choose the specific service.

I've used your code and have updated the values of my drop downs to no avail. I also tried experimented with the delay. Hoping you can help me troubleshoot

 https://fife-sunflower-68mk.squarespace.com/appointment-enquiry (pw: elipsis)

Grateful for any insight you might have!

Link to comment
  • Solution

@mbockmaster Wrote new code that takes a different approach. It uses method chaining and uses some descriptive methods with the following pattern:


In the example code below, you'll instantiate a new ToggleFields() class. Then run the id() method by passing in the value of the "id" or "name" attribute of the parent field. Then run the hasValues() method by passing in an array of values that are expected to trigger the dependency field to show. Then the last method to run is the thenShow() method which is an array of id's take from the "id" attribute of the fields that are needing to be hidden or shown. 

JavaScript

 
(function () {

  const DELAY = 500; // Delays code execution so other scripts can run
  const SLIDE_UP_SPEED = 0; // Speed in milleseconds
  const SLIDE_DOWN_SPEED = 200; // Speed in milleseconds

  setTimeout(() => {

    const field = new ToggleFields();

    field
      .id('select-7e5087e2-19de-427f-9bab-9ed57e548c5d-field')
      .hasValues([
        'Registered massage therapy',
      ])
      .thenShow([
        'select-f65e7041-7c99-4cb3-b089-e9363ba0b0bb'
      ]);

    field
      .id('select-7e5087e2-19de-427f-9bab-9ed57e548c5d-field')
      .hasValues([
        'Face',
      ])
      .thenShow([
        'checkbox-897fc44a-47cc-4187-a9a3-2c07eac942cd'
      ]);

    field
      .id('select-7e5087e2-19de-427f-9bab-9ed57e548c5d-field')
      .hasValues([
        'Body',
      ])
      .thenShow([
        'checkbox-d05a8b96-5202-43d7-9c62-bbf68ee166f4'
      ]);
    
    field
      .id('select-7e5087e2-19de-427f-9bab-9ed57e548c5d-field')
      .hasValues([
        'Nails',
      ])
      .thenShow([
        'checkbox-9b633fdd-ed93-4173-9e68-0219fc67502f'
      ]);

    
    field
      .id('select-84584693-059c-4a6b-82f4-002531232b32-field')
      .hasValues([
        'Registered massage therapy',
      ])
      .thenShow([
        'select-cb6f6cab-fb33-498c-b4e5-8c025e64982b'
      ]);
    
    field
      .id('select-84584693-059c-4a6b-82f4-002531232b32-field')
      .hasValues([
        'Face',
      ])
      .thenShow([
        'select-92778fbb-eb9b-45a9-bf16-ae2d9b531611'
      ]);

  }, DELAY);


  /*********************************************************************
   * DO NOT ALTER BELOW THIS LINE UNLESS YOU KNOW WHAT YOU'RE DOING
   *********************************************************************/

  class ToggleFields {

    constructor() {
      this.parentEl = null;
      this.parents = {};
      this.dependenciesFields = [];
      this.values = [];
      this.showFields = [];
      this.valueMapping = null;
    }

    id(id) {
      if (typeof id == 'string') {

        // Get the parent element 
        const parentFieldId = document.querySelector('[id="' + id + '"]');
        const parentFieldName = document.querySelector('[name="' + id + '"]');
        let parent;
        
        if (parentFieldId) { this.parentEl = parentFieldId; }
        if (parentFieldName) { this.parentEl = parentFieldName }
        
        this.parentEl.valueMap = this.parentEl.valueMap || {};
        this.parents[this.parentEl.id || this.parentEl.name] = this.parentEl;
        
        if(!this.parentEl) {
          return this;
        }
        
      }

      return this;
    }

    hasValues(values) {
      if (!Array.isArray(values)) { return this; }

      this.values = values;

      if(this.parentEl) {
        values.forEach(value => {
          this.parentEl.valueMap[value] = this.parentEl.valueMap[value] ||  {
            fields: [],
            hidden: true
          };
        })
      }

      return this;
    }

    thenShow(fields) {

      if (!Array.isArray(fields)) { return this; }
      
      if(this.parentEl) {
        fields.forEach(field => {
          this.values.forEach(key => {
            this.parentEl.valueMap[key].fields.push(`#${field}`);
          });
        });
      }

      const fieldIds = fields.map(field => '#' + field);
      $(fieldIds.join(',')).hide();
      
      this.onLoad(() => {
        // Load jQuery if not loaded
        if (!window.jQuery) { return this.loadJquery(this.thenShow(fields)) }

        this.showFields = fields;

        // Assign jQuery to a variable
        const $ = jQuery;

        Object.keys(this.parents).forEach(id => {

          const parentEl = this.parents[id];

          if (!parentEl || parentEl.toggleFieldInit) { return; }
        
          parentEl.toggleFieldInit = true;
          // Show or hide the dependent field based on the PARENT_VALUE
          $(parentEl).on('change', (evt) => {
            const value = evt.target.value;
            
            Object.keys(parentEl.valueMap).forEach(key => {
              if(parentEl.valueMap[key].hidden == false) {
                $(parentEl.valueMap[key].fields.join(',')).slideUp(SLIDE_UP_SPEED);
                parentEl.valueMap[key].hidden = true;
              }
            })

            if(parentEl.valueMap[value]) {
              $(parentEl.valueMap[value].fields.join(',')).slideDown(SLIDE_DOWN_SPEED);
              parentEl.valueMap[value].hidden = false;
            }
          });

        });
      })

      return this;
    }

    loadJquery() {
      var s = document.createElement('script');
      s.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
      s.onload = this.thenShow(this.fields);
      document.body.appendChild(s);
    }

    onLoad(callback) {
      // Initialize after the page has been loaded
      if (document.readyState === 'complete') {
        setTimeout(callback, DELAY)
      } else {
        document.addEventListener("DOMContentLoaded", function () {
          setTimeout(callback, DELAY);
        }, false);
      }
    }

  }

})();

 

Edited by jpeter

Full stack developer who loves helping people out with anything web related. If you'd like to support me, buy me a coffee!

Link to comment
On 10/13/2023 at 6:57 PM, jpeter said:

@mbockmaster Wrote new code that takes a different approach. It uses method chaining and uses some descriptive methods with the following pattern:


In the example code below, you'll instantiate a new ToggleFields() class. Then run the id() method by passing in the value of the "id" or "name" attribute of the parent field. Then run the hasValues() method by passing in an array of values that are expected to trigger the dependency field to show. Then the last method to run is the thenShow() method which is an array of id's take from the "id" attribute of the fields that are needing to be hidden or shown. 

You'll want to instantiate a new ToggleFields class for each field. I've commented out the 2 other fields for now, but you can uncomment them and add in the proper values for each method. 

JavaScript

(function () {

  const DELAY = 500;

  setTimeout(() => {

    const field = new ToggleFields();
    // const field2 = new ToggleFields();
    // const field3 = new ToggleFields();

    field
      .id('select-7e5087e2-19de-427f-9bab-9ed57e548c5d-field')
      .hasValues([
        'Registered massage therapy',
        'Other'
      ])
      .thenShow([
        'select-a5cb5d87-35c0-499e-8dc7-5eb6873fa86d'
      ]);

    // field2
    //   .id('select-7e5087e2-19de-427f-9bab-9ed57e548c5d-field')
    //   .hasValues([
    //     'Registered massage therapy',
    //     'Other'
    //   ])
    //   .thenShow([
    //     'select-a5cb5d87-35c0-499e-8dc7-5eb6873fa86d'
    //   ]);

    // field3
    //   .id('select-7e5087e2-19de-427f-9bab-9ed57e548c5d-field')
    //   .hasValues([
    //     'Registered massage therapy',
    //     'Other'
    //   ])
    //   .thenShow([
    //     'select-a5cb5d87-35c0-499e-8dc7-5eb6873fa86d'
    //   ]);


  }, 0);


  /*********************************************************************
   * DO NOT ALTER BELOW THIS LINE UNLESS YOU KNOW WHAT YOU'RE DOING
   *********************************************************************/

  class ToggleFields {

    constructor() {
      this.parentEl = null;
      this.dependenciesFields = [];
      this.values = [];
      this.showFields = [];
    }

    id(id) {
      if (typeof id == 'string') {

        // Get the parent element 
        const parentFieldId = document.querySelector('[id="' + id + '"]');
        const parentFieldName = document.querySelector('[name="' + id + '"]');
        let parent;

        if (parentFieldId) { this.parentEl = parentFieldId; }
        if (parentFieldName) { this.parentEl = parentFieldName }
        if (!parent) return this;
      }

      return this;
    }

    hasValues(values) {
      if (!Array.isArray(values)) { return this; }

      this.values = values;

      return this;
    }

    thenShow(fields) {

      if (!Array.isArray(fields)) { return this; }

      this.onLoad(() => {
        // Load jQuery if not loaded
        if (!window.jQuery) { return this.loadJquery(this.thenShow(fields)) }

        this.showFields = fields;

        // Assign jQuery to a variable
        const $ = jQuery;

        // Create ID CSS selectors based on the DEPENDENT_ID.
        var ids = fields.map(id => '#' + id);

        ids.forEach(id => {
          // Get the dependent element
          var $dependentField = $(id);

          // Hide the text field on page load
          $dependentField.hide();
        });

        if (!this.parentEl) { return; }

        // Show or hide the dependent field based on the PARENT_VALUE
        $(this.parentEl).on('change', (evt) => {
          if (this.values.includes(evt.target.value)) {
            $(ids.join(',')).slideDown();
          } else {
            $(ids.join(',')).slideUp();
          }
        });
      })

      return this;
    }

    loadJquery() {
      var s = document.createElement('script');
      s.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
      s.onload = this.thenShow(this.fields);
      document.body.appendChild(s);
    }

    onLoad(callback) {
      // Initialize after the page has been loaded
      if (document.readyState === 'complete') {
        setTimeout(callback, DELAY)
      } else {
        document.addEventListener("DOMContentLoaded", function () {
          setTimeout(callback, DELAY);
        }, false);
      }
    }

  }

})();

 

 

Wow @jpeter, thank you SO much for this! I'm very close (I think!), as the fields are hidden. But they aren't appearing. Any idea what I'm missing? 

 

Screen Shot 2023-10-16 at 1.41.26 PM.png

Link to comment
18 minutes ago, jpeter said:

@mbockmaster Looks like the same id is being used, "select-7e5087e2-19de-427f-9bab-9ed57e548c5d-field" , for the field.id() method. You'll want to make sure it's the ID of each select field. image.thumb.png.ac2b3626654912aaaf150189b2d54982.png

Hi @jpeter, thanks for the reply! I'm hoping to have a different field appear based on the selection. For example, if the user selects 'Registered massage therapy', then the registered massage therapy services check boxes will appear. If they select 'Body', then the body services check boxes will appear. Is that possible?

Link to comment
20 hours ago, jpeter said:

@mbockmaster I've updated the code in this comment to account for having the same field show and hide different fields based on it's value.  

 

 

Thank you for this! I've replaced the code with your update, but it doesn't seem to be running (all of the check boxes are displaying below the drop down). In my page header code injection, I've put in a script for the 3.5.1 jquery library (simply because I haven't figured out where to access an updated library link) and I see that your code references 3.6.0. Could this be the issue? I'm out of my depth when it comes to Jquery but so grateful for your time and help.

Screen Shot 2023-10-18 at 11.33.50 AM.png

Link to comment

 

1 hour ago, mbockmaster said:

... I've replaced the code with your update, but it doesn't seem to be running (all of the check boxes are displaying below the drop down). In my page header code injection, I've put in a script for the 3.5.1 jquery library (simply because I haven't figured out where to access an updated library link) and I see that your code references 3.6.0. Could this be the issue? I'm out of my depth when it comes to Jquery but so grateful for your time and help.

@mbockmaster Updated the JS code here to account for the DELAY variable. The reason it wasn't working is due to our code running too soon and so we needed to allow time for the form's code to run first before running our custom code.  

Full stack developer who loves helping people out with anything web related. If you'd like to support me, buy me a coffee!

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

×
×
  • Create New...

Squarespace Webinars

Free online sessions where you’ll learn the basics and refine your Squarespace skills.

Hire a Designer

Stand out online with the help of an experienced designer or developer.