shiDMV Posted June 6, 2022 Share Posted June 6, 2022 (edited) 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 June 6, 2022 by shiDMV melaniejaane 1 Link to comment
jpeter Posted June 6, 2022 Share Posted June 6, 2022 (edited) @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> QF6rBF69qS.mp4 Edited June 6, 2022 by jpeter Uploading video example tuanphan, melaniejaane and shiDMV 1 2 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
shiDMV Posted June 6, 2022 Author Share Posted June 6, 2022 4 hours ago, jpeter said: @shiDMV The javascript code below should work for you. This worked beautifully, thank you so much! tuanphan and Belizabeth 2 Link to comment
ratkaj Posted May 17, 2023 Share Posted May 17, 2023 @jpeterI'm attempting to do the same but I'm stuck. Website -- https://www.academyforlittlelearners.com/time-off I'm hoping to implement if the answer below is no... (required) Yes No Then the following is shown: I am requesting part of the day off From in Central Time To in Central Time Can you help? Link to comment
jpeter Posted June 7, 2023 Share Posted June 7, 2023 (edited) @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); }; })() Pr0Qp5aRAs.mp4 Edited June 7, 2023 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
JamesonW Posted June 24, 2023 Share Posted June 24, 2023 (edited) 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 June 24, 2023 by JamesonW Wrong parent id Link to comment
paul2009 Posted June 24, 2023 Share Posted June 24, 2023 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 ⬇️ JamesonW 1 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
jpeter Posted June 24, 2023 Share Posted June 24, 2023 (edited) @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); }; })(); SK6f4epaKF.mp4 Edited July 4, 2023 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
JamesonW Posted June 25, 2023 Share Posted June 25, 2023 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
JamesonW Posted June 25, 2023 Share Posted June 25, 2023 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); }; })(); SK6f4epaKF.mp4 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
jpeter Posted June 26, 2023 Share Posted June 26, 2023 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
JamesonW Posted June 26, 2023 Share Posted June 26, 2023 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 belowhttps://www.leanagilesensei.com/contact Form Logic Test.mov Link to comment
jpeter Posted July 4, 2023 Share Posted July 4, 2023 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 belowhttps://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. JamesonW 1 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
JamesonW Posted July 5, 2023 Share Posted July 5, 2023 (edited) Thanks @jpeter - after your updated code and killing some other code elsewhere in the site - it seems to be working!! Edited July 5, 2023 by JamesonW Revision Link to comment
Dovely2023 Posted August 28, 2023 Share Posted August 28, 2023 Hi @jpeter we have a client who is looking to add some conditional logic to their site as well, so when someone selects "other" a text field populates. I tried various versions of the code mentioned above, but nothing is working. Any tips would be greatly appreciated. Thank you! Website URL is: https://www.bodronfruit.com/contact Link to comment
jpeter Posted August 28, 2023 Share Posted August 28, 2023 (edited) @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. oIBVZzMRC5.mp4 Edited August 28, 2023 by jpeter Dovely2023 1 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
Dovely2023 Posted August 29, 2023 Share Posted August 29, 2023 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. oIBVZzMRC5.mp4 72.97 kB · 0 downloads That worked perfectly. Thank you so much for your help @jpeter! Link to comment
mbockmaster Posted October 11, 2023 Share Posted October 11, 2023 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 jpeter Posted October 13, 2023 Solution Share Posted October 13, 2023 (edited) @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); } } } })(); 7Vz7ShBQiQ.mp4 Edited October 20, 2023 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
mbockmaster Posted October 16, 2023 Share Posted October 16, 2023 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); } } } })(); 7Vz7ShBQiQ.mp4 810.49 kB · 1 download 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? Link to comment
jpeter Posted October 16, 2023 Share Posted October 16, 2023 @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. 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
mbockmaster Posted October 16, 2023 Share Posted October 16, 2023 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. 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
jpeter Posted October 17, 2023 Share Posted October 17, 2023 @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. YKsZ60LatH.mp4 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
mbockmaster Posted October 18, 2023 Share Posted October 18, 2023 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. YKsZ60LatH.mp4 511.18 kB · 0 downloads 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. Link to comment
jpeter Posted October 18, 2023 Share Posted October 18, 2023 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
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment