How to get all key/values from a select box in javascript

Here is the demo on how we can get all the keys and values from a drop-down box.


A select box:

<select id = "country">
        <option value="">-- Select --</option>
        <option value="value1" selected>India</option>
        <option value="value2">United State</option>
	<option value="value3">Malaysia</option>
</select>


Get all option texts:

var e = document.getElementById("country");
var result = "";
for (i = 0; i < e.length; i++) {
	if(!e.options[i].text.match(/select/gi)){
		result = result + e.options[i].text + "<br>";
	}
}


Get all the values:

var e = document.getElementById("country");
var result = "";
for (i = 0; i < e.length; i++) {
	if(e.options[i].value){
	      result = result + e.options[i].value + "<br>";
	}
}


Full code:

<!DOCTYPE html>
<html>
	<head>
		<title>JavaScript - Get all values from dropdown list</title>
	</head>

	<body>

		<h1>JavaScript - Get all values from dropdown list</h1>

		<p id="result"></p>
		
		<select id = "country">
			<option value="">-- Select --</option>
			<option value="value1" selected>India</option>
			<option value="value2">United State</option>
			<option value="value3">Malaysia</option>
		</select>

		<script>

			function GetAllValues(){
				var e = document.getElementById("country");
				var result = "";
				for (i = 0; i < e.length; i++) {
					if(e.options[i].value){
						result = result + e.options[i].value + "<br>";
					}
				}
				
				document.getElementById("result").innerHTML = result;
			}

			function GetAllTexts(){
				var e = document.getElementById("country");
				var result = "";
				for (i = 0; i < e.length; i++) {
					if(!e.options[i].text.match(/select/gi)){
						result = result + e.options[i].text + "<br>";
					}
				}
				
				document.getElementById("result").innerHTML = result;
			}
			
		</script>

		<br/>
		<br/>
		<button type="button" onclick="GetAllValues()">Get All Values</button>

		<button type="button" onclick="GetAllTexts()">Get All Text/Keys</button>
	</body>

</html>


Demo:

JavaScript – Get all values from dropdown list

JavaScript – Get all values from dropdown list



Leave a Reply