EN
JavaScript - get selected text and value from option select on change
5 points
In this article, we would like to show you how to get a select element value on a change event using JavaScript.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
5
</head>
6
<body>
7
<select id="my-dropdown-id">
8
<option value="1">Blue</option>
9
<option value="2" selected>Green</option>
10
<option value="3">Red</option>
11
<option value="4">Yellow</option>
12
</select>
13
<script>
14
15
$(document).ready(function() {
16
var element = $('#my-dropdown-id');
17
18
element.change(function() {
19
var selection = $('option:selected', element); // $(':selected', element);
20
21
var value = selection.val();
22
var text = selection.text();
23
24
console.log('value: ' + value + ', text: ' + text);
25
});
26
});
27
28
</script>
29
</body>
30
</html>
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
5
</head>
6
<body>
7
<select id="my-dropdown-id">
8
<option value="1">Blue</option>
9
<option value="2" selected>Green</option>
10
<option value="3">Red</option>
11
<option value="4">Yellow</option>
12
</select>
13
<script>
14
15
$(document).ready(function() {
16
var element = $('#my-dropdown-id');
17
18
element.change(function() {
19
var selection = element.find("option:selected"); // element.find(":selected");
20
21
var value = selection.val();
22
var text = selection.text();
23
24
console.log('value: ' + value + ', text: ' + text);
25
});
26
});
27
28
</script>
29
</body>
30
</html>
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
5
</head>
6
<body>
7
<select id="my-dropdown-id">
8
<option value="1">Blue</option>
9
<option value="2" selected>Green</option>
10
<option value="3">Red</option>
11
<option value="4">Yellow</option>
12
</select>
13
<script>
14
15
$(document).ready(function() {
16
var element = $('#my-dropdown-id');
17
18
element.change(function() {
19
var options = element.prop('options');
20
21
// below code uses pure JavaScript
22
23
var index = options.selectedIndex;
24
25
if(index == -1) {
26
console.log('Option is not selected.');
27
} else {
28
var option = options[index];
29
30
var value = option.value;
31
var text = option.label
32
33
console.log('value: ' + value + ', text: ' + text);
34
}
35
});
36
});
37
38
</script>
39
</body>
40
</html>