0

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 https://permaink.myshopify.com/pages/contact with the store PW = "help".

enter image description here

isherwood
  • 58,414
  • 16
  • 114
  • 157
sabah
  • 111
  • 1
  • 11

1 Answers1

1

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).

Woodrow
  • 2,740
  • 1
  • 14
  • 18
  • I implemented your script but how do I change the event from a window load to every time a change is made in the Name field? Your code hides the Comment field but it does not reappear when I type a value into the Name field. – sabah Apr 01 '22 at 19:51
  • @sabah - you would need to bind an `onchange` event listener to the Name field input, so that when change event is triggered, you could check the input value is not empty and then show the comment field again. See some examples at: https://stackoverflow.com/questions/574941/best-way-to-track-onchange-as-you-type-in-input-type-text – Woodrow Apr 04 '22 at 17:32