简体   繁体   中英

Populate Select Box with Clickable Links

I have a PHP, JS, AJAX app that I am trying to finish off. I have a select box that populates from the files in a server-side folder. Works okay but I am trying to make the select box options clickable or on hover. A better solution might be to use AJAX to contact a PHP little page that provides a list of files in JSON to be given back to the JavaScript, and have this AJAX run when triggered by a hover listener I don't know enough php syntax to get it working and have tried many methods (well one, but different variations on it), the most recent is in the comments. Ideally I would also like it to only populate by file name , in the format year-month-day, in descending order. This is the code I have. Very grateful for any assistance.

Tried what is in the comments and many variations.

<?php
$files = scandir('upload/');
sort($files);
echo "<select>";
foreach($files as $file){
   //echo'<a href="upload/'.$file.'">'.$file.'</a>'";
   echo "<option value=' $file'> $file </option>";
}
echo "</select>";
?>

For anyone that is interested this is all working now. I made quite a few changes to the correct/accepted answer. The code is as follows:

The css (I wanted the drop-down button look like a standard/default button so removed css for it):

/* The container <div> - needed to position the dropdown content */
.dropdown {
  position: relative;
  display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
  display: none;
  position: absolute;
  background-color: #ECF0F1;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
  white-space: nowrap;
}

/* Links inside the dropdown */
.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

/* Change color of dropdown links on hover */
.dropdown-content a:hover {background-color: #ddd;}

/* Show the dropdown menu on hover */
.dropdown:hover .dropdown-content {display: block;}

The php, jquery and ajax:

<div class="dropdown">
  <button class="dropbtn" id="file-browser">Latest Timesheet</button>
  <div class="dropdown-content" id="file-list">

<?php
  $files = array_slice(scandir('upload/'), 2);
  rsort($files);
  foreach ($files as $file) {
    $file = pathinfo($file)['filename'];
     echo "<a href='upload/$file'>$file</a>";
}  
?>
</div>
</div>

<script>
    $("#file-browser").hover(
  function (e) {
  $.ajax({
    url: "my_dropdown_data.php",
    dataType: "json",    
    success: function(response) {    
      $("#file-list").html(""); //Clear current file list
      response.forEach(
        function(file) {
           $("#file-list").append("<a href='upload/" + file + "'>" + file.substr(0, file.length - 4) + "</a>");
        }
      );
    },
    error: function(response) {
      console.log(response);
    }
    })
  }
);
</script>

The external php file (my_dropdown_data.php):

<?php
  $files = array_slice(scandir('upload/'), 2);
  rsort($files);
  echo json_encode($files);
?>

Building off of the dropdown menu from the guide from w3schools as well as your own code. This is an alternative to using a <select> menu and having to build out a bit of JavaScript to make it work similar to a dropdown menu, which would be poor practice.

!!! One note before anything , this is directly taking from file names stored in your uploads directory. If you do not properly sanitize / randomize file names that are being uploaded, it's possible a user could escape this HTML and set up an XSS attack - please care for the file names on upload to avoid this.

You'll first set up the base HTML structure, this is what will be used for an asynchronous, reloading dropdown menu:

<div class="dropdown">
  <button class="dropbtn" id="file-browser">Dropdown Menu ACTIVATE</button>
  <div class="dropdown-content" id="file-list">
  </div>
</div>

And now you'll fill in the data for a static, not reloading dropdown menu:

<div class="dropdown">
  <button class="dropbtn">Dropdown Menu ACTIVATE</button>
  <div class="dropdown-content">

  <?php
  $files = scandir('upload/');
  sort($files);
  foreach ($files as $file)
     echo "<a href='upload/$file'>$file</a>";
  ?>

  </div>
</div>

And finally, you have your CSS, directly from w3schools - these are the important bits to build off of:

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  z-index: 1;
}

.dropdown-content a {
  display: block;
}

.dropdown:hover .dropdown-content {
  display: block;
}

Now to get it to load data dynamically, you don't have to load the data initially since it will just be overwritten, but we do need a listener for when the button is hovered over (and the dropdown should be shown). That will be accomplished with jQuery's .hover() :

$("#file-browser").hover(
  function {

  }
);

Now we want to load the data, which we'll do utilizing AJAX; more specifically jQuery's .ajax() :

$("#file-browser").hover(
  function {
    url: "my_dropdown_data.php",
    dataType: "json",
    success: function(response) {

    },
    error: function(response) {
      console.log(response);
    }
  }
);

The data will come from the file my_dropdown_data.php from above, and that will be essentially the same code from the static data dropdown, except echoed out as JSON:

  <?php
  $files = scandir('upload/');
  sort($files);
  echo json_encode($files);
  ?>

And the final piece of the puzzle will be all the JS -hover listener, AJAX call- with processing of the data to list out the JSON list of files from our PHP:

$("#file-browser").hover(
  function {
    url: "my_dropdown_data.php",
    dataType: "json",
    success: function(response) {
      $("#file-list").html(""); //Clear current file list
      response.forEach(
        function(file) {
          $("#file-list").append("<a href='upload/" + file + "'>" + file + "</a>");
        }
      );
    },
    error: function(response) {
      console.log(response);
    }
  }
);

And voila, there you have your dropdown menu, and when hovered over the data will load from the PHP file and populate the dropdown with links to the files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM