Skip to content Skip to sidebar Skip to footer

Populating A Dropdown List With Values From A Text File

I am trying to populate a dropdown list with values from a text file. I have the following code, however, I am not getting any thing within the dropdown list. Can anyone help me? H

Solution 1:

1.your current code page must be a .php page.(extension of the page need to be .php)

2.change code like below:-

<?php
//remove <script></script> and add php start and close tag
//comment these two lines when code started working fine
error_reporting(E_ALL);
ini_set('display_errors',1);

$filename = 'pytxt.txt';
$eachlines = file($filename, FILE_IGNORE_NEW_LINES);

?>
<body>
    <div id="page-wrap">
        <h1>Pulls from text files</h1>
        <select id="value">
            <option selected value="base">Please Select</option>
           <?php foreach($eachlines as $lines){ //add php code here
                echo "<option value='".$lines."'>$lines</option>";
            }?>
        </select>
    </div>
</body>

Solution 2:

Since it seems like you want a jQuery/HTML answer...

  1. Use ajax to read your text file
  2. Split the data into an array (A JS function that performs a similar operation to the PHP function explode)
  3. Append each of your options to your select list.
<head>
  <script>
    $.get('pytxt.txt'),
      function(data) {
        console.log(data); /* Open the console too see the data */
        var options = data.split(','),
          /* Something to "explode" by. See link. */
          $select = $('select#value');
        for (var i = 0; i < options.length; i++) {
          $select.append('<option value="' + i + '">' + options[i] + '</option>"');
        }
      }, "text");
  </script>
</head>

<body>
  <div id="page-wrap">
    <h1>Pulls from text files</h1>
    <select id="value">
                <option selected value="base">Please Select</option>
            </select>

  </div>
</body>

Solution 3:

To catch up your code you could do some like

<?php
    $filename  = 'pytxt.txt';
    $eachlines = file($filename, FILE_IGNORE_NEW_LINES);
    $select    = '<select name="value" id="value">';
    foreach($eachlines as $lines)
    {
        $options .= "<option>{$lines}</option>";
    }
    $select .= $options . "</select>";
?>

And than you can add it to your html. This all should be in the same php file. (not recommended way!)

<body>
<div id="page-wrap">
    <h1>Pulls from text files</h1>
    <?php echo $select; ?>

</div>
</body>

even if this is nasty source! I recomment to seperate php from html. But catching up to your source this could look like this.


Post a Comment for "Populating A Dropdown List With Values From A Text File"