2

Here is my CSS:

#optionHotel{
    display:none;
}

Here is my JavaScript:

function cb1(type){
    switch(type){
        case "hotel":
            alert("hotel");
            $("#optionHotel").css("display","block");
            break;
    }
}

Here is my Html:

<div id="optionHotel"> Some Element In here</div>

Start Script in 'Head Tag':

<?echo '
<script>window.onload = cb1("'.$orderType.'");</script>
'?>

<!--CSS-->
<link href="../../css/navigate.css" rel="stylesheet"/>
<link href="../../css/reservation.css" rel="stylesheet"/>

Passing data from php to js is ok because I have checked In the switchcase

with alert() it's ok but I don't know why .css display to block doesn't work

please advice, Thank in advance

2
  • 2
    That's because DOM is not ready yet you are calling the function immediately, ie before your element is added to DOM. window.onload = function(){ cb1("orderType") } Commented May 19, 2013 at 12:39
  • $("#optionHotel").hide(); Commented May 19, 2013 at 12:40

1 Answer 1

7

Your code:

<script>window.onload = cb1("'.$orderType.'");</script>

will call the cb1() function immediately and try to assign its result as the window.onload handler. You see the alert because the function does run, but because it runs immediately from inside the head of the document the document body has not yet been parsed so the script can't find your element.

You need to assign an actual function as the handler, where that function will be run onload and at that point will call cb1():

<script>window.onload = function() { cb1("'.$orderType.'"); };</script>

Or, since you are using jQuery, and assuming you don't want to wait for images to load before calling your function, use a document ready handler:

<?echo '
<script>
  $(document).ready(function() {
     cb1("'.$orderType.'");
  });
</script>
'?>

...or move the script to the end of the body and call your function directly:

<?echo '
<script>cb1("'.$orderType.'");</script>
'?>
Sign up to request clarification or add additional context in comments.

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.