简体   繁体   中英

Hide DIV when input field is blank

I wonder if you could help me with an issue.

I am building a content template for an events page, that pulls data through using Advanced Custom Fields.

I have a field in the admin side which will be filled out when adding a new event. The field is called show_info with the ID #acf-editor-46 .

On some events however this will be left blank, but the DIV that wraps around the content on the frontend will still show on the template, the DIV has the class .show-info-wrapper .

I would like it so when the show_info field is blank, the DIV .show-info-wrapper does not display on the front end.

I have made some progress from browsing around, you can see the code I have so far here:

HTML (Just a quick testing set up):

<textarea id="acf-editor-46" class="wp-editor-area" aria-hidden="true">1111</textarea>
<div class="show-info-wrapper">CONTENT</div>

JavaScript + jQuery:

$(document).ready(function() {

    if($('#acf-editor-46').val() == '' ){$('.show-info-wrapper').hide();}  

    $('#acf-editor-46').on('change' , function() {

         if( this.value != ''){

               $('.show-info-wrapper').show(); 
          }
          else{
               $('.show-info-wrapper').hide(); 
         }
    });
  });

It works on JSFiddle ( http://jsfiddle.net/ha2nedfb/ ), however, it seems that on my WordPress site as the input and the DIV are not on the same DOM, it does not work.

Could anyone help me with this?

Thank you!

Just change the event of #acf-editor-46 to input .

$(document).ready(function() {

    if($('#acf-editor-46').val() == '' ){$('.show-info-wrapper').hide();}  

    $('#acf-editor-46').on('input' , function() {  // Just change event to input

         if( this.value != ''){

               $('.show-info-wrapper').show(); 
          }
          else{
               $('.show-info-wrapper').hide(); 
         }
    });
  });
if (!$("#acf-editor-46").val()) {
// textarea is empty
}

try this to check textarea is empty or not

You can delegate event if textarea is rendered later.

$(document).on('change', '#acf-editor-46', callback);

Links:

  1. https://api.jquery.com/on/
  2. https://learn.jquery.com/events/event-delegation/

Assuming the <textarea> and <div> are really siblings in this very order (your text contradicts the example) & if you're OK with adding a placeholder to the textarea & you only need new-ish browsers , there is a pure CSS solution:

<textarea ... placeholder=" "> </textarea>
.show-info-wrapper {
  display: block;
}

.wp-editor-area:placeholder-shown + .show-info-wrapper {
  display: none;
}

Here's a pen .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM