How can you remove all options from the HTML select drop down and add option values using JavaScript

You can use the following code which will do the following

  1. Remove all option elements in the HTML select drop down.
  2. Add option elements to the HTML select drop down.

The above can be done in both jQuery and vanilla JavaScript. I will be using vanilla JavaScript in this example.  Please review following code.


<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="src/style.css">
<script type="text/javascript">
function check_curr(obj) {
document.getElementById("currency").innerHTML = null;
if (obj.value == 'UK') {
console.log('UK country selected');
daySelect = document.getElementById('currency');
daySelect.options[0] = new Option('Select', '');
daySelect.options[1] = new Option('British Pound', 'GBP');
}
else {
console.log('US country selected');
daySelect = document.getElementById('currency');
daySelect.options[0] = new Option('Select', '');
daySelect.options[1] = new Option('US Dollar (USD)', 'US$');
}
}
</script>
</head>
<body>
<form name="frm">
<p>
<select name="country" size="1" id="country" onchange="javascript:check_curr(this)">
<option value="">Select</option>
<option value="UK">United Kingdom</option>
<option value="US">USA</option>
</select>
</p>
<p>
<select name="currency" size="1" id="currency">
<option value="GBP">British Pound</option>
<option value="USD">US Dollar</option>
</select>
</p>
</form>
</body>
</html>

You can this example in action here

 

Leave a Reply

Your email address will not be published. Required fields are marked *