Show an hidden div based on its selected ID

I have a local webpage to show my classes with their students, one at a time (carousel-like), with this code:

<script type="text/javascript">
    var currentIndex = 0;
 
    window.addEventListener("load", function () {
        postsArray = document.getElementById("posts").value;
        postsArray = JSON.parse(postsArray);
 
        renderTitle();
    });
 
    function showPrevious() {
        currentIndex--;
 
        var previous = document.querySelector(".post.active").previousElementSibling;
        document.querySelector(".post.active").className = "post";
        previous.className = "post active";
 
        renderTitle();
    }
 
    function showNext() {
        currentIndex++;
 
        var next = document.querySelector(".post.active").nextElementSibling;
        document.querySelector(".post.active").className = "post";
        next.className = "post active";
 
        renderTitle();
    }        
 
    function renderTitle() {
        document.querySelector(".previous-post").style.visibility = "hidden";
        document.querySelector(".next-post").style.visibility = "hidden";
 
        if (postsArray[currentIndex + 1] != null) {
            document.querySelector(".next-post").style.visibility = "visible";
            document.getElementById("next-post-title").innerHTML = postsArray[currentIndex + 1].title;
        }
 
        if (postsArray[currentIndex - 1] != null) {
            document.querySelector(".previous-post").style.visibility = "visible";
            document.getElementById("previous-post-title").innerHTML = postsArray[currentIndex - 1].title;
        }
    }
</script>

<?php
    require "$root/PDO_connect.inc";
    
    $sql = $pdo->query("
    SELECT c.ID_classe, c.classe, c.anno_nascita, c.imagelink, c.imagemap, c.mapname, c.note, s.cognome, s.nome, s.dati_personali, s.abitazione 
    FROM studenti__classi c
    INNER JOIN studenti s
    WHERE s.ID_classe = c.ID_classe 
    ORDER BY c.ID_classe
    ");
    $classi = $sql->fetchAll(PDO::FETCH_GROUP);
    $count = 0;
    $posts = array();
 foreach($classi as $classe => $students) { 
     printf("<div id=\"" . $classe . "\" data-value=\"" . $classe . "\" class=\"post " . ($count++ == 0 ? 'active' : '') . "\">
     <div class='left'> 
     <h2>" . $students[0]['classe'] . "  (<span class='min'>" . $classe . "</span>) - nati nel: <b>" . $students[0]['anno_nascita'] ."</b></h2>\n
     <p>" . $students[0]['note'] . "</p>\n
     " . $students[0]['imagemap'] . "
     <p><img class='expansible fl' alt='immagine della classe' tabindex='1' usemap='" . $students[0]['mapname'] . "' src='" . $students[0]['imagelink'] . "' /></p>\n
     </div>");
     echo "
     <div class='right'>\n
     <table class='tabella sortable'>\n
     <thead><tr><th>cognome</th><th>nome</th><th>abitazione</th><th>note</th></tr></thead>\n
     <tbody>
     ";
     foreach($students as $student) {
         printf("<tr><td><b>$student[cognome]</b></td> <td>$student[nome]</td><td>$student[abitazione]</td><td>$student[dati_personali]</td></tr>");
    }
    echo "</tbody>\n</table>\n
    </div>\n</div>";
 }
?>

  <input type="hidden" id="posts" value="<?php echo htmlentities(json_encode($posts)); ?>">
 </div>
 
  <div id="piede">
  
   <span onclick="showPrevious();"><b>previous class</b></span>
   <span id="previous-post-title"></span>
  - . - . -
   <span onclick="showNext();"><b>next class</b></span>
   <span id="next-post-title"></span>
   ** - **
   
   <!-- **the following is just an attempt, probably not correct, because, there is already, above other js code** -->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select class="form-control" name="attribute_pa_license" id="uniqueid">
     <option value="s043" class="attached enabled">s043</option>
     <option value="gol3" class="attached enabled">gol3</option>
   </select>
   
  </div>

As a result I have now many divs, each with its own id. All are invisible, except one, the one with “active” class, as expected.
Now, I would like to learn how to apply (with js) the class “active” to a given id (selected with a select - option html tag, possibly).
Someone could help me?

You’ve got the code there in your example, you just have to tweak it.

var selectedID = document.getElementById("idGoesHere");
    selectedID.className = "post active";

Of if you’re doing it with a function, use a variable instead of a hard coded value…

var selectedID = document.getElementById(variableName);
    selectedID.className = "post active";
1 Like

Thank you.
But, I am not an expert of javascript: how I should write (/call) that code within an <option> tag?

Some times the best way to learn is to try :wink: but it would be something like this…

document.getElementById('selectfieldId').addEventListener('change', function() {

  // remove the active class from the other elements
  document.querySelector(".post.active").className = "post";
  
  // IF the value of the select is the direct id of the div...
  // if the name is not in the value, you'll have to adjust the this.value part
  var selectedID = document.getElementById(this.value);
  selectedID.className = "post active";

});
2 Likes

I did it! Thank you very much!
This the code:

function selectId() {
    document.getElementById('selectfieldId').addEventListener('change', function() {

    // remove the active class from the other elements
    document.querySelector(".post.active").className = "post";
  
    // IF the value of the select is the direct id of the div...
    // if the name is not in the value, you'll have to adjust the this.value part
    var selectedID = document.getElementById(this.value);
    selectedID.className = "post active";
    });
    }

and then:

   <select class="form-control" id="selectfieldId" onChange="selectId();">
     <option value="">--Please choose an option--</option>
     <optgroup label="some label">
      <option value="gol3">some name</option>
     </optgroup>
     <optgroup label="some label">
      <option value="s42">some name</option>
      <option value="s43">other name</option>
     </optgroup>
   </select>

You shouldn’t need that part with the event listener. They should do the same thing…

1 Like

If I remove that code, it does not work anymore :neutral_face:

That’s because you wrapped the event listener in a function. You need one or the other, not both.

1 Like

You are right: the trick was to put your script at the end of the file.
Thank you!

2 Likes

It’s best practice to put ALL scripts at the end of the file. This allows the DOM to be loaded before the scripts are run, so all elements are available to run against.

1 Like

I have a further question, but I don’t know if put it here or open a new thread. Someone could tell me what I should do?
The question is: it would be possible to set a given div visible (by setting its class as ‘active’, with a javascript command) from an external (php/html) link?
So far I open a php (local) webpage with this code http://localhost/scuola/hashtag-classi.php?tag=gol3. And it works, but I get only one class.
It would be possible to get non only that class (as that code can do), but all my classes, with only one visible, that is as if (to remaining in the example in this thread) I selected in <select> tag, the <option> value was gol3 (I mean <option value="gol3">).
In other words: it would be possible to set an option value of a select tag in web page from an external link?
In this way, keeping (almost all) the code already given, I could a) have only one (php) file (while now I have two php files: one to browse all my classes and one to show only one, coming from another php file) and, mainly, b) even opening a given class (gol3), I could easily browse all other, if I want.
Thank you.

You could, but I’m not sure why you would.

Remember, javascript should always add capability, not be dependent on them. So putting a display element dependent on JS may be a mistake because people can run with JS disabled. I know of at least three people who only turn JS on if they absolutely have to, even in this day and age.

3 Likes

Thank you. The webpage we are speaking about, is only in localhost. So the problem should not be present.

I’m still not sure I understand exactly what you’re trying to do, or what value it would provide, but to set the value of a select object is simply setting the value of the select element to one of the option values.

This is the same basic concept except I’m using buttons instead of calling an external page. The value in the change function is what you would need to use with the value returned from your ajax call.

1 Like

Thank you. Yes, your code do what I want, but within a (the same) page.
What code should I use to get it working from a link in an external page? Something like: <a href="my-path/myfile/[and here?]">open-gol3</a>.

The code in the destination page is, as said above:

 <script type="text/javascript">
document.getElementById('selectfieldId').addEventListener('change', function() {
    document.querySelector(".post.active").className = "post";
 
    var selectedID = document.getElementById(this.value);
    selectedID.className = "post active";
    });
 </script>

I’m still not getting what you want to do. You can’t affect a permanent change on a different page than what you’re on without doing some sort of file system (localDB, db, etc) change.

If you’re looking to use the output from a link to an external page, then you’re talking about using an ajax pattern. There are MANY threads on that topic here, so search for some examples, give it a shot and post if you have further problems.

Essentially, you’ll have to make the ajax call, get the results back from the call, then use that as the value passed to the function instead of what was in the button code I gave you.

1 Like

If I’m understanding correctly, you want to link to the page and have different parts of it visible.
It is possible for JavaScript to do that based on the querystring, where it examines that querystring and adjust the presentation of the page based on what is there.

1 Like

Thank you. Yes, indeed: a querystring. I will see next days how to do.

Today, after searching about querystring, I tried this code, re-using the working js code, but unsuccessfully:

    if ( url.indexOf( '?value' ) !== -1 ) { 
     document.querySelector(".post.active").className = "post";
     var selectedID = document.getElementById(this.value);
     selectedID.className = "post active";}

I tried also this

    const urlParams = new URLSearchParams(window.location.search);
    const cla = urlParams.get('cla');
    document.getElementById('selectfieldId').value = cla;

and in the address bar of the browser http://my-path/my-file?cla=gol3

Using Dave’s example from post #14 this seems to work fine.

const urlParams = new URLSearchParams(window.location.search);
const cla = urlParams.get('cla');
change(cla);
1 Like