apaillarse
apaillarse

Reputation: 85

Limiting number of options displayed by a php populated dropdown menu

I have a drop-down menu as following:

   <select onchange="random_function()" id='choice' >
      <option selected="selected" >
         Make a choice
      </option>
  </select>

I populate it through a php request inside the <select> tag as following:

<?php
    include 'config.php';
    $query = $pdo->query('
                SELECT choices
                FROM allTheChoices'   
    );
    while ($row = $query->fetch()){
       echo "<option>".$row['choices']."</option>";
    }
?>

For the moment, my database is uncomplete and I have only 2 options to display but there will be plenty in the future (100+).

My goal is to find a way to let the select only show 10 options and it should display a scroll bar to see all the remaining options.

I already tried using <select size="10"> but the design of the dropdown is completely changed and awful. Do you have a simple way to do this without altering the design?

Upvotes: 0

Views: 663

Answers (2)

apaillarse
apaillarse

Reputation: 85

Used this bit of code to achieve what I wanted :

 <select  style="position:absolute;" onmousedown="if(this.options.length>8)
{this.size=8;}"  onchange='this.size=0;' onblur="this.size=0;" >

Make sure to use the following to avoid container div to expand when choosing an option :

style="position:absolute;"

and edit the following code with the number of choices you want to display (10 is used in this example) :

onmousedown="if(this.options.length>10){this.size=10;}"

So the whole html code I used is :

  <select  style="position:absolute;" onmousedown="if(this.options.length>8)
    {this.size=8;}"  onchange='this.size=0;' onblur="this.size=0;" >
          <option selected="selected" >
             Make a choice
          </option>
  </select>

Upvotes: 1

pacificpelican
pacificpelican

Reputation: 363

Try using a limit in your SQL statement, like this: "LIMIT 10".

So this is how the code might look:

<?php
include 'config.php';
$query = $pdo->query('
            SELECT choices
            FROM allTheChoices
            LIMIT 10' 
);
while ($row = $query->fetch()){
   echo "<option>".$row['choices']."</option>";
} ?>

Upvotes: 0

Related Questions