0

I'm having some difficulties getting Javascript to execute in a PHP statement if it is possible at all. Below I have the code, if the field 'First' is empty, then the background color of a certain div will be yellow. How can I get this to work properly if it is possible in the first place? Thanks in advance.

if (empty($_POST["First"])) {

    echo '<script type="text/javascript">';
    echo '$("div").css({"background-color":"yellow"});';
    echo '</script>';

} 
7
  • Is there a reason you're not doing this check in javascript instead of PHP? Commented Apr 4, 2017 at 11:27
  • No particular reason, I was just wondering if it is possible and if so, how to achieve it. Commented Apr 4, 2017 at 11:28
  • Consider adding a class to the div in PHP, and then having that class in CSS to set the background colour. Commented Apr 4, 2017 at 11:29
  • Also, something that it is going to really help you is to use like that <?php if (empty($_POST["First"])) { ?> <script type="text/javascript"> $("div").css({"background-color":"yellow"}); </script> <?php } ?> Commented Apr 4, 2017 at 11:29
  • What is the difficulty? It looks correct assuming you have loaded jQuery before the statement. Any console errors? Commented Apr 4, 2017 at 11:30

2 Answers 2

1

check this code. hope it will help you

<div>Content Div</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
 //$_POST["First"] = ''; if you want to check this code execute then remove comment then run this code
 if (empty($_POST["First"])) {
echo '<script type="text/javascript">';
echo '$("div").css("background-color","yellow");';
echo '</script>';
}
?>

you can also use this code

<div>Content Div</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
//$_POST["First"] = ''; this is for test case if you want to check then remove comment then run this code
 if (empty($_POST["First"])) { ?>
<script type="text/javascript">
$("div").css("background-color","yellow");
</script>
<?php } ?>

in this code php tag and javascript tag use separate

Sign up to request clarification or add additional context in comments.

Comments

0

You should try putting script tags inside php tags, like this:

<?php 
    if (empty($_POST["First"])) { ?>
        <script type="text/javascript">
        '$("div").css({"background-color":"yellow"});';
        </script>
<?php } ?>

Here is an example: https://stackoverflow.com/a/13254287/7808973

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.