I have a drop-down menu that populates from a text file a
, and additionally gets data that is needed from the same text file.
<?php
$file_handle = fopen("/path/to/a.txt", "rb");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode(',', $line_of_text);
echo "<option value='".$parts[1]."".$parts[2]."'>".$parts[0]."</option>";
}
fclose($file_handle);
?>
</select>
What I need is an additional drop down menu where the users choose to populate from a.txt
or b.txt
, but at doing the selection of a
or b
dynamically changes the other drop down menu.
答案 0 :(得分:0)
I would use jquery/javascript to do this as follows:
index.php would contain the initial dropdown box to choose either a or b. Then bind an event to that drop down box 'change' event. This would fire a function to call a second file ajax.php that would return the contents of your file in the example based on the data sent in the ajax call which you would load into an empty tag in your index page.
index.php
<select id='choice'>
<option value='a'>A</option>
<option value='b'>B</option>
</select>
<select id='choice2'></select>
<script>
$(document).ready(function(){
$('#choice').on('change',null,doFill);
});
function doFill(){
$.ajax({
url:'ajax.php',
type:'post',
dataType:'html',
data: { choice: $('#choice').val() },
success: function(response){
$('#choice2').html(response);
}
});
}
</script>
ajax.php
<?php
$file = "/path/to/a.txt";
if($_POST['choice'] == 'b'){
$file = "/path/to/b.txt";
}
$file_handle = fopen($file, "rb");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode(',', $line_of_text);
echo "<option value='".$parts[1]."".$parts[2]."'>".$parts[0]." </option>";
}
fclose($file_handle);
?>
答案 1 :(得分:0)
作为一种替代方法,接受的答案(我认为这是一种很好的方法),你也可以在页面加载时使用PHP预生成select元素的备用选项(或者一个单独的select元素),并简单地隐藏使用CSS在初始页面加载时不希望看到的元素。在第一个表单上的选择操作时,您将根据需要取消隐藏/隐藏第二个下拉元素。如果下拉列表中的项目相对较少,这可能是一种更简单的方法,因此在页面加载时下载两个列表不会为HTML添加一堆额外的大小。