I have a dropdown button for filtering the data. The value of the dropdown list will contain the categories of a column from the dataset.
I already have a function to get the categories from the dataset, now I just want to add it to the dropdown list.
This is my code for add new option to the dropdown button:
<script type="text/javascript">
function addOption() {
optionText = 'Premium';
optionValue = 'premium';
$('#select1').append(`<option value="${optionValue}">
${optionText}
</option>`);
}
</script>
This is the code for dropdown list:
<form class="simple_form form-inline" method="get">
<div class="form-group select required">
<label for="basic-url" class="form-label">Product</label>
<select class="select required form-control" id="select1" onclick="addOption()">
<option value="">- Discipline -</option>
<option value="1">HW</option>
<option value="2">SW</option>
</select>
</div>
</form>
How to make the dropdown add the option once, because with my code, whenever I click the button, it will add the option again.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://d3js.org/d3.v6.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"
integrity="sha512-d9xgZrVZpmmQlfonhQUvTR7lMPtO7NkZMkA0ABN3PHCbKA5nqylQ/yWlFAyY6hYgdF1Qh6nYiuADWwKB4C2WSw=="
crossorigin="anonymous"></script>
</head>
<body>
<form class="simple_form form-inline" method="get">
<div class="form-group select required">
<label for="basic-url" class="form-label">Product</label>
<select class="select required form-control" id="select1" onclick="addOption()">
<option value="">- Discipline -</option>
<option value="1">HW</option>
<option value="2">SW</option>
</select>
</div>
</form>
<script type="text/javascript">
function addOption() {
optionText = 'Premium';
optionValue = 'premium';
$('#select1').append(`<option value="${optionValue}">
${optionText}
</option>`);
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
</body>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…