Reputation: 33
I need to create a web page where the user has to select from a dropdown list a value for different categories as shown below.
<div class ="SurveyFormContainer">
<label for ="cat1">category 1</label>
<select>
<option value=0>1</option>
<option value=1>2</option>
<option value=2>3</option>
<option value=3>4</option>
<option value=4>5</option>
</select>
<br>
<label for ="cat2">category 2</label>
<select>
<option value=0>1</option>
<option value=1>2</option>
<option value=2>3</option>
<option value=3>4</option>
<option value=4>5</option>
</select>
</div>
I need to add a lot of different categories, so my question is: is there a way to reuse the same set of options without having to replicate the code each time?
I'm quite new with html, I've tried to search for solutions online but could not find anything... thanks for the help!
Upvotes: 3
Views: 4559
Reputation: 196
You're not able to do this with HTML alone, you will need another piece of technology to help you do this.
There are many ways to achieve this, such as using a server-side programming language (C#, PHP, JavaScript) or on the front-end using JavaScript.
If you opt for a server-side approach then you can assign the common options to a variable and perform a for(each) loop for the select boxes that share those values.
For example, in PHP:
<?php
$sharedOptions = [
0 => 1,
1 => 2,
2 => 3,
3 => 4,
4 => 5
];
?>
<!DOCTYPE html>
<html>
<body>
<div class="SurveyFormContainer">
<label for="cat1">Cat 1</label>
<select id="cat1" name="cat1">
<?php foreach($sharedOptions as $key => $value) { ?>
<option value="<?php echo $key ?>">
<?php echo $value ?>
</option>
<?php } ?>
<option>Only for Cat 1</option>
</select>
<label for="cat2">Cat 2</label>
<select id="cat2" name="cat2">
<?php foreach($sharedOptions as $key => $value) { ?>
<option value="<?php echo $key ?>">
<?php echo $value ?>
</option>
<?php } ?>
<option value="50">Only for Cat 2</option>
</select>
</div>
</body>
</html>
Upvotes: 2
Reputation: 11055
You can use JavaScript (or Jquery) to assign a series of Html to a group of elements.
$(document).ready(function(){
var items={option1:{value:1,text:1},option2:{value:2,text:2}}
//You may narrows the selector to an exact class e.g. $(".mySelect") instead of $("select")
$.each(items, function (i, item) {
$('select').append($('<option>', {
value: item.value,
text : item.text
}));
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Selection 1:
<select name="select1" class="mySelect"></select>
<br><br>
Selection 2:
<select name="select2" class="mySelect"></select>
<br><br>
Besides do not forget to set name for <select>
if there are multiple selects.
Upvotes: 0