Syam Danda
Syam Danda

Reputation: 587

Dynamically add number of options in a Dropdown list

I have a number value which is coming from my database. I want to display a dropdown list based on the count of the number. For example if the number is 5 then i need to display 1-5 options in dropdown list. Can any one guide me on this?

Thanks for your responses.

Upvotes: 1

Views: 1151

Answers (4)

Ricky jani
Ricky jani

Reputation: 21

Please first search your thought in google. I give you example in php If Your database give response like 5 Than write code like

<select>
<?php $i=5;
for($i;$i<=5;$i++)
{ 
echo "<option>".$i."</option>";
}?>
</select>

Upvotes: 2

Aamir
Aamir

Reputation: 355

The alternate solution for @theglossy1 solution.
This is useful when you want to concatenate large no. of options,
use array for string Concatenation

<form>
<select id="myid"></select>
</form>
<script>
 var number=5;
 var ArrayoptionList = []; //Array of Option list
 for (var x=1; x<=number; x++) {
  ArrayoptionList.push("<option>"+x+"</option>");
 }
 $("select#myid").html(ArrayoptionList.join(""));
</script>

Refer below link

High Performance Concatenation in Javascript

Upvotes: 0

Muhammad Nasir
Muhammad Nasir

Reputation: 2204

There are number of way you can do it some of them are

$('select').append($('<option>', {value:1, text:'One'}));

or

  $('select').append('<option val="1">One</option>');

or

 var option = new Option(text, value);
    $('select').append($(option));

Upvotes: 0

theglossy1
theglossy1

Reputation: 553

If your database returns 5 and puts it in the variable "number" you could do this:

<form>
<select id="myid"></select>
</form>
<script>
 var number=5;
 var optionList = "";
 for (var x=1; x<=number; x++) {
  optionList += "<option>"+x+"</option>";
 }
 $("select#myid").html(optionList);
</script>

Upvotes: 2

Related Questions