Question


Hello, community. Is it possible to specify a drop-down list structure at one place and to use it for several drop-down lists? For example, I need 5 drop-down lists all comprising 3 entries: "Basic", "Advanced", "Professional". Do I really need to write the following 5 times?

<select id="myid" name="myname" size="1"> 
    <option value="1">Basic</option>
    <option value="2">Advanced</option>
    <option value="3">Professional</option>
</select>



BR
Ewgenij

Was it helpful?

Solution

I have done something similar recently.

It is simple. Look at my code below which I used to automatically enter dates for a select dropdown:

<select id="dateDropdown"></select> /*give an id for select*/

<script type="text/javascript">
var dateSelectId = document.getElementById("dateDropdown"); /*get the select element by its id*/

for (var i = 0; i < 8 ; i++) { /*for loop to create the options - in my case 8 options */
     var currentDate = moment().subtract('d',i).format("MMM D"); /*ignore this - it basically just gives different dates for me*/

     var paramObj = { /*declaring an obj for the 'option' tag's parameters*/
         'optValue':i, /*value for the 'option' tag*/
         'optText':currentDate /*text for 'option' tag*/
     };

     optionGenerator(dateSelectId,paramObj); /*function which actually creates <option> tags and assigns the parameters to it*/
}; 

Below is my javascript file which I import which contains the optionGenerator() function

/*Function to dynamically create select list and adding options to it*/

var optionGenerator = function(selectId,paramObj){

    var optionInstance = document.createElement("option"); //creates child <option> element
    optionInstance.value = paramObj.optValue;
    optionInstance.text = paramObj.optText;
    selectId.options.add(optionInstance); //adds the <option> tag with desired values
};

Let me know if you understood.

OTHER TIPS

With php you can do like this

$select_box = "<select id='myid' name='myname' size='1'> 
                <option value='1'>Basic</option>
                <option value='2'>Advanced</option>
                <option value='3'>Professional</option>
            </select>";

echo $select_box ;// where-ever you want in between your HTML tags

?>

eg,

<form >
<?php  echo $select_box ; ?>
...other inputs...
</form>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top