Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

javascript - Shopify - Debut Theme - Showing A Textbox if Certain Variant is Selected

I'm trying to show my "Embossing" textbox only when the "Style" dropdown option "Embossing" is selected. I've added the below code in my new template, product-customizable-template.liquid, which created the textbox but I want to hide it unless "Embossing" is selected.

<p class="line-item-property__field">
<label for="embossing">Embossing</label>
<input required class="required" id="embossing" type="text" name="properties[Embossing]">
</p> 

"Style" Dropdown

The Style textbox has the following code:

<select class="single-option-selector single-option-selector-product-customizable-template product-form__input" id="SingleOptionSelector-0" data-index="option1">
<option value="None" selected="selected">None</option>
<option value="Embossing">Embossing</option>
<option value="Stamp">Stamp</option>
</select>

I am still working on the site, so it is not active right now.

Any help would be greatly appreciated, thank you!

question from:https://stackoverflow.com/questions/65650222/shopify-debut-theme-showing-a-textbox-if-certain-variant-is-selected

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to check on-page load and on change of select box using Javascript and you can add and remove custom code to form easily

You can check and try the below snippet for a better idea

// on change test for your condition
document.getElementById('SingleOptionSelector-0').addEventListener('change', function (e) {
   _checkAndAppend();
});

// run on page load and check the for value and add if selected value meet condition
_checkAndAppend();

function _checkAndAppend() {
   var item = document.getElementById('SingleOptionSelector-0');
   var itemValue = document.getElementById('SingleOptionSelector-0').value;
   if (itemValue == 'Embossing') { 
      var input = `<p class="line-item-property__field _embossing">
            <label for="embossing">Embossing</label>
            <input required class="required" id="embossing" type="text" name="properties[Embossing]">
            </p> `;
      item.parentNode.insertAdjacentHTML('beforeend',input);
   } else {
      if(document.querySelector('._embossing')){
         document.querySelector('._embossing').remove();
      }      
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...