Support

Account

Home Forums General Issues Show element if field is empty using javascript

Solved

Show element if field is empty using javascript

  • Hi, I have an element with and id of message that I want to hide when a custom field (video_id) is met and show itself when the custom field is empty. Can this be done? Could it be done possibly with javascript?

    Here is my code:

    
    <p id="message">Video unavailable</p>
    <script></script>
    
  • 
    if (get_field('video_id')) {
      ?><script></script><?php 
    } else {
      <p id="message">Video unavailable</p>
    }
    
  • Thanks for helping but actually, I meant for the function to be inside the <script> tag.

    Maybe something like this?:

    
    
    <p id="message"></p>
    
    <script>
    if (get_field('video_id')) {
      ?><?php 
    } else {
    
    	document.getElementById("message").innerHTML = "Video unavailable";
    
    	// Only display "Video unavailable when field "video_id" is empty"
    	
    }
    </script>
    

    The code above does not work I think because the plugin I am using does not support php. I need to do it with javascript if that is possible.

  • 
    <script>
      <?php 
        if (get_field('video_id')) {
          ?>
            // JS to run if there is a value
          <?php 
         } else {
          ?>
            // JS to run if there no value
          <?php 
        }
      ?>
    </script>
    
  • It still isn’t working. This code is being put in shortcode content by the shortcoder plugin btw if it helps.

  • Usually for shortcodes you need to return the value to be displayed. This can be don using output buffers.

    
    ob_start();
    
    // your code here
    
    return ob_get_clean();
    
  • It still doesn’t seem to work. I am just going to do it without shortcodes and use the code you posted earlier. Thank you for helping.

Viewing 8 posts - 1 through 8 (of 8 total)

You must be logged in to reply to this topic.