Home > Enterprise >  How to hide form fields with Jquery in Shopify
How to hide form fields with Jquery in Shopify

Time:04-02

I am trying to write a simple script which follows the logic below but I am having difficulties.

If "Name" field =  blank

Then Hide "Comment" field

Else Show "Comment" field

$(document).ready(function() {
  if ($('#ContactForm-name').value() == "") {
    $('#ContactForm-body').hide();
  } else {
    $('#ContactForm-body').show();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Can someone please help me? I provided a screen shot of the form and its HTML.

The shopify store is enter image description here

CodePudding user response:

Taking a look at the example link you provided w/ 'help' password, it doesn't look like jQuery is actually loaded on the site, after running the following in console: console.log(typeof window.jQuery) returns undefined.

You may need to use vanilla JS to achieve what you're trying to do (or side load jQuery, if you have permissions to do so and really need to use it).

Using JS without jQuery, you can try doing something like:

window.addEventListener('load', function() {
   if (document.getElementById('ContactForm-name').value === '') { 
      document.getElementById('ContactForm-body').style.display = 'none';
   } else {
      document.getElementById('ContactForm-body').style.display = 'block';
   }
});

Note, that just hiding the ContactForm-body textarea will still leave a border outline and the label Comment showing, so you may need to do more than just hiding the textarea (find the parent <div> in JS and hide whole block).

  • Related