Home › Forums › General Issues › 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.
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.