简体   繁体   中英

Add a new dropdown menu dynamically HTML/PHP

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.

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);
?>

As an alternate approach the the accepted answer (which I do believe is a good approach), you could also pregenerate the alternate options for the select element (or a seperate select element altogether) using PHP on page load and simply hide the elements you don't want visible on initial page load using CSS. On selection action on first form you would unhide/hide second dropdown elements as necessary. This may be a simpler approach if you have relatively few items in the dropdowns such that downloading both lists on page load does not add a bunch of extra size to the HTML.

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