In this article I will explain with example, how to use AngularJS to get multiple selected Text and Value of HTML Multiple Select ListBox when Button is clicked using ng-click directive.
AngularJS Get selected Text and Value of HTML Multiple Select ListBox
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The AngularJS app HTML DIV consists of an HTML Multiple Select ListBox and a Button. The HTML Multiple Select ListBox is populated from JSON array using ng-options directive.
The Button has been assigned ng-click directive. When the Button is clicked, the GetValue function of the Controller gets called.
Inside the function, a loop is executed over the ng-model attribute values and the selected Value is fetched. The selected Text is fetched from the JSON array using jQuery grep function.
Finally the selected Text and Value of all the selected options are displayed using JavaScript alert message box.
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
$scope.Fruits = [{
Id: 1,
Name: 'Apple'
}, {
Id: 2,
Name: 'Mango'
}, {
Id: 3,
Name: 'Orange'
}];
$scope.GetValue = function () {
var message = "";
for (var i = 0; i < $scope.ddlFruits.length; i++) {
var fruitId = $scope.ddlFruits[i];
var fruitName = $.grep($scope.Fruits, function (fruit) {
return fruit.Id == fruitId;
})[0].Name;
message += "Value: " + fruitId + " Text: " + fruitName + "\n";
}
$window.alert(message);
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<select multiple = "multiple" ng-model="ddlFruits" ng-options="fruit.Id as fruit.Name for fruit in Fruits">
</select>
<br />
<br />
<input type="button" value = "Get" ng-click = "GetValue()" />
</div>
</body>
</html>
Screenshot
Demo
Downloads