2

I have a jquery script that loads on document ready and I want to display a hidden popup if a user has already clicked a button (button field). But the condition I check is with php code.

<script>
$( document ).ready(function() {
  if (<?php $user_fields->field_button['und'][0]['value'] = 1 ?>) {
    var popup = document.getElementById("testpopup1").style.visibility = "visible";
    alert("x");
  }
});
</script>

But this way doesn't work. Is there a way to put the php code inside the if statement of my jquery code or I have to try something else?

0

2 Answers 2

2

You don't need Javascript to do an if and all.

In your HTML

<?php if ($user_fields->field_button['und'][0]['value'] === 1) { ?>

    <div id="testpopup1">Your content</div>

    <script>alert('x');</script>

<?php } ?>
Sign up to request clarification or add additional context in comments.

9 Comments

And the onload function?The php tags should be both at the start and the end of the if statement? And I have this code at the node--XX.tpl.php file
Ok, I got it! you only missed the '=1' at the if statement, but it totally worked. I mixed js and php and I messed up, but your answer worked!
$(document).ready() is unnecessary here since you don't even use jQuery inside your JavaScript. Don't forget to upvote and mark the answer as solved if it helped ;)
I can't upvote because I lack reputation but I mark it as solved!
Actually, the divs and the script load in both cases, even if the value is one and not
|
1

Save the value of the PHP value in a Javascript variable.

$(document).ready(function() {
  var undValue = <?= $user_fields->field_button['und'][0]['value'] ?>;
  if (undValue === 1) {
    document.getElementById('testpopup1').style.visiblity = 'visible';
    alert('x');
  }
});

3 Comments

I don't know much about php, but I think that the <?= part is wrong, right?Should I replace it with <?php instead?
In fact, <?= is equivalent to <?php you can use both. But I would suggest you to be explicit and use <?php
@ArgirisA It's a shorthand for <?php echo. It definitely works.

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.