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!
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With