<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>selected demo</title>
<style>
div {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<select name="education" multiple="multiple">
<option>BSc</option>
<option selected="selected">BA</option>
<option>MSc</option>
<option selected="selected">MA</option>
<option>MCA</option>
</select>
<div>
</div>
<script>
$( "select" ).change(function() {
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).text() + " ";
});
$( "div" ).text( str );
})
.trigger( "change" );
</script>
</body>
</html>
Explantion:
In this example all selected items from the select option are displayed in a div. each() function is like an Iterator which allows to iterate over a set of elements. In this example a change event is attached to select that gets the text for each selected option and writes them in the div. The change event occurs when the value of an element has been changed (only works on <input>, <textarea> and <select> elements). The change() method triggers the change event, or attaches a function to run when a change event occurs. In this example, trigger method is also attached to select which triggers the change event for select initially i.e the trigger() method triggers the specified event.
0 Comment(s)