Reputation: 1
I'm trying to make a dynamic drop down list using HTML and JavaScript, but every time I click on the drop down I get a new set of duplicate values. How can I prevent this from happening? I would prefer to stick to vanilla JS and html
function yearsArray(num) {
let years=document.getElementById("years")
let year=[...Array(num+1).keys()]
year.shift()
year.shift()
year.forEach(element => {
switch (element) {
case 1:
years.add(new Option(element,element,true))
break;
default:
years.add(new Option(element,element,false))
break;
}
})
}
body{
font-family: Arial, Helvetica, sans-serif;
}
h1{
color: gray;
}
<!DOCTYPE html>
<head>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<title>Simple Interest Calculator</title>
<body>
<div class="maindiv">
<h1>Simple Interest Calculator</h1>
<form>
<label for="principal">Amount</label>
<input type="number" name="principal" id="principal"> <br/>
<label for="rate">Interest Rate</label>
<input type="range" id="rate" name="rate" min="0" max="20" step=".25">
<span id="rate_val">10.25%</span> <br/>
<label for="years">No. of Years </label>
<select id="years" name="years" onclick="yearsArray(20)">
<option selected value="1">1</option>
</select><br/>
<!-- Interest : <span id="result"></span><br/> -->
<button type="submit">Compute Interest</button>
</form>
</div>
</body>
</html>
Upvotes: 0
Views: 70
Reputation: 1
Figured it out. added the javascript function to the body tag
<body onload=yearsArray(20)></body>
Upvotes: 0
Reputation: 3453
Just run that function once on page load:
(You could of course just create the options using markup)
function yearsArray(num) {
let years = document.getElementById("years")
let year = [...Array(num + 1).keys()]
year.shift()
year.shift()
year.forEach(element => {
switch (element) {
case 1:
years.add(new Option(element, element, true))
break;
default:
years.add(new Option(element, element, false))
break;
}
})
}
yearsArray(20); //<---------- This runs the function on page load
body {
font-family: Arial, Helvetica, sans-serif;
}
h1 {
color: gray;
}
<!DOCTYPE html>
<head>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<title>Simple Interest Calculator</title>
<body>
<div class="maindiv">
<h1>Simple Interest Calculator</h1>
<form>
<label for="principal">Amount</label>
<input type="number" name="principal" id="principal"> <br/>
<label for="rate">Interest Rate</label>
<input type="range" id="rate" name="rate" min="0" max="20" step=".25">
<span id="rate_val">10.25%</span> <br/>
<label for="years">No. of Years </label>
<select id="years" name="years">
<option selected value="1">1</option>
</select><br/>
<!-- Interest : <span id="result"></span><br/> -->
<button type="submit">Compute Interest</button>
</form>
</div>
</body>
</html>
Upvotes: 2