I have a script that allows the selection of a directory from a drop down select and then displays its subdirectories in another drop down select. I am trying to check if the selected directory has sub directories, and if so, display a message indicating whether or not there are subdirectories available, ie, "no subdirs"
or "subdirs"
.
The problem is that the alert message is displayed for the last element selected from the directories drop down, rather than the current directory selection.
For example, if the current selection is directory 2, and the previous selection was directory 1, document.getElementById("subdir").options.length;
is shown for directory 1, rather than directory 2. I'm not sure, where the problem is, so any assistance would be greatly appreciated, thanks.
<script type='text/javascript'>
$(function() {
$("#dirs").on('change', function() {
var Dir = $(this).val();
//Make an ajax call
$("#subdir").html('<option>Loading...</option>');
$.get("ajax.php?Dirs=" + encodeURIComponent(Dir), function(data) {
$("#subdir").html(data);
});
});
});
</script>
<script>
function myFunction() {
var y = document.getElementById("subdir").options.length;
alert(y);
if (y <= 1) {
alert('no subdirs');
} else if (y > 1) {
alert('subdirs');
}
}
</script>
<select id="dirs" name="Dirs" onChange="myFunction()">
<option value="" selected="selected" disabled="yes">Select Directory</option>
<?php
$dirs = glob("/*", GLOB_ONLYDIR);
foreach($dirs as $val){
echo '<option value="'.$val.'">'.basename($val)."</option>
";
}
?>
</select>
<select name="subdir" id="subdir" required>
<option value="Select Sub Directory" selected="selected" disabled="yes">Select Sub Directory</value>
</select>
And ajax.php:
<?php
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//Check for passed dir exist
$folder = $_GET['Dirs'];
if(!file_exists($folder)) {
exit('Folder Not Found');
}
$out = '';
$files = array_filter(glob($folder.'/*'), 'is_dir');
echo '<option value="Select Sub Directory" selected="selected" disabled = "yes">Select Sub Directory</value>';
foreach($files as $val){
$out .= '<option value="'.$val.'">'.basename($val)."</option>
";
}
//Output the file options
exit($out);
}
?>