Pradeep
Pradeep

Reputation: 33

How to add auto increment number to select tag?

$x = date("");

function add_nol($number,$add_nol)
{
   while (strlen($number)<$add_nol)
   {
      $number = "0".$number;
   }

   return $number;
}

for($y=10;$y<=50;$y++)
{
   echo "<select name='id'>";
   echo "<option value='". $x."".add_nol($y,3)."'>" . $x."".add_nol($y,3) ."</option>";
   echo "</select>";
}

I want to add auto increment numbers into select tag, but I am getting drop down for each numbers from the above code. How to fix this error?

Upvotes: 0

Views: 3725

Answers (2)

Sherin Jose
Sherin Jose

Reputation: 2516

You are repeatedly creating the select tag inside the loop , thats y the select boxes are created instead of option tags. Edit the for loop as:

echo "<select name='id'>";
for($y=10;$y<=50;$y++){       
    echo "<option value='". $x."".add_nol($y,3)."'>" . $x."".add_nol($y,3) ."</option>";      
}
echo "</select>";

Upvotes: 0

Amal Murali
Amal Murali

Reputation: 76636

Two things to remember:

  • The <select> element is used to create a drop-down list.
  • The <option> tags inside the <select> element define the available options in the list.

With your current code, the generated HTML markup would be similar to this:

<select name='id'>
    <option value='010'>010</option>
</select>
<select name='id'>
    <option value='011'>011</option>
</select>
...

This is incorrect. You are creating a separate dropdown on each loop iteration. You only need one <select>tag - they should go outside the loop.

echo "<select name='id'>";
for($y=10;$y<=50;$y++)
{
    echo "<option value='". $x."".add_nol($y,3)."'>" . $x."".add_nol($y,3) ."</option>";
}
echo "</select>";

Demo

Upvotes: 1

Related Questions