简体   繁体   中英

If PHP echo code returns a value then run script. Else nothing

I have the following code which returns the result I require inside of a tab. But because the JavaScript is in the same file it shows a blank tab when there is no data to show. I remove the JavaScript and the tab disappears. How can I run the JavaScript only if data is present so the tab will disappear? Or can I call it from another file?

<?php echo $block->escapeHtml($block->getProduct()->getData($this->getCode()));
?>
<script type="text/JavaScript">
    var commareplace = document.querySelectorAll("div > #bikefitment");
    for (var i = 0; i < commareplace.length; i++) {
        commareplace[i].innerHTML = commareplace[i].innerHTML.replace(/,/g, "<br />");
    }
</script>

My knowledge on PHP is not the best, so I will just describe it like that.

  • Just save the data in a variable
  • If the data exists (eg is not empty)
    • Print data and JavaScript code
  • If it does not exist, do nothing

Here is some pseudo-code:

<?php
data = $block->escapeHtml($block->getProduct()->getData($this->getCode()));

if (data exists) {
    echo data;
    echo /* Your JavaScript Code*/;
}
?>

Since you have to hide the tab if escapeHtml() returns empty value. So you can create a condition block to add the script if escapeHtml() returns a non-empty value.

<?php $EH = $block->escapeHtml($block->getProduct()->getData($this->getCode()));
if ($EH) {

echo $EH;
?>
<script type="text/JavaScript">
    var commareplace = document.querySelectorAll("div > #bikefitment");
    for (var i = 0; i < commareplace.length; i++) {
        commareplace[i].innerHTML = commareplace[i].innerHTML.replace(/,/g, "<br />");
    }
</script>

<?php } ?>

Use a if statement that within the php tags that check value id present then you can render the the java script tags as well as the value.

<?php 
    $val = $block->escapeHtml($block->getProduct()->getData($this->getCode()));  
    $script =  '<script type="text/JavaScript">
                    var commareplace = document.querySelectorAll("div > #bikefitment");
                    for (var i = 0; i < commareplace.length; i++) {
                        commareplace[i].innerHTML = commareplace[i].innerHTML.replace(/,/g, "<br />");
                    }
                </script>';
    if($val != "" || $val !=null)
    { 
       echo $val; 
       echo $script;
    }
?>

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