0

I am trying to make a function in PHP that is like JavaScript's alert() command, but the OK button's onclick attribute is not working!

Here is my code:

<!DOCTYPE html>
<?php
 function alert($title, $text) {
 $html = '<div id="alert" style="background-color:lightGray; text-align:center; height:500px; width:500px; color: black; position:fixed; top: 50%; left:50%; margin-left:-250px; margin-top:-250px;">';
 $html = $html . '<h1 style="background-color:red; border-radius: 15px;">'. $title . '</h1>' . $text;
 $html = $html . '<br><br><button type="button" style="border-radius:25px; height:50px; width:100px; background-color:white; border:none;" onclick="document.getElementById(\"alert\").style.display=none">OK</button>';
 echo $html;
 }
 alert('Testing', 'Testing <em>testing</em><b>123</b>');
?>

What is wrong? I get an "alert box" but the OK button doesn't work!

asked Nov 28, 2013 at 17:20
3
  • if you're calilng this multiple times, you'll have multiple divs with the same id, and only the FIRST found id will ever get returned by document.getElementById(). Commented Nov 28, 2013 at 17:22
  • That's a quote mismatch in the ID selector ! Commented Nov 28, 2013 at 17:23
  • @MarcB raises a valid point. If you have two alert boxes on the same page both of them will close one of them, which is strange. Generate a unique id every time you render an alert box. Commented Nov 28, 2013 at 17:27

2 Answers 2

2

element.style.display = 'none' instead of just none

ps just want to be clear of javascript concept

answered Nov 28, 2013 at 17:23
Sign up to request clarification or add additional context in comments.

2 Comments

' will give a conflict with the existing string delimiter. You have to escape it at least once.
1

Change to:

document.getElementById(\"alert\").style.display=\"none\"

I guess this also shows that your current approach is quite terrible. Having to add all those escapes without code highlighting is annoying.

See if you can find a way to do it properly ;) (hint: you can).

answered Nov 28, 2013 at 17:22

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.