Search code examples
javascriptphpjqueryshow-hide

PHP script JQuery grabs wrong number of elements


I've been using JQuery to show/hide elements based on login-status, however I've run into some unexpected results, here's the code:

<script>
    $(document).ready(function(){
        $("#uploadform").hide();
    });
</script>

This hides the form if the user is not logged in.

    <h2 id="needlogon"> You need to be logged in </h2>
    <a id="needlogon" href="index.php"> Back to start </a>

These are to be shown only if the user is not logged in

<?php
if (isset($_SESSION['cid'])){
   echo '<script>
           $(document).ready(function(){
           $("#uploadform").show();
           $("needlogon").hide();
           });
         </script>';
}
?>

The uploadform is shown/hid as intented, but the needlogon elements are not hidden when the condition ($_SESSION['cid']) is set. The only way it works is if i change the ID's of the elements to needlogon1 and needlogon2, and changing the JQuery to:

<?php
if (isset($_SESSION['cid'])){
   echo '<script>
           $(document).ready(function(){
           $("#uploadform").show();
           $("#needlogon1").hide();
           $("#needlogon2").hide();
           });
         </script>';
}
?>

I'm sure I'm just missing something silly, anyone know what it is?


Solution

  • For starters, your jQuery selector is off:

    // $("needlogon").hide();
    $("#needlogon").hide(); // you forgot the #
    

    Having said that, you're using an ID -- which is supposed to be unique. You might want to change the two usages of needlogin to a class instead of id, and then your selector would be .needlogon like so:

    $(".needlogon").hide();