dragonfly dragonfly - 4 months ago 7
Javascript Question

How to pass select option label field's value or selected text to a functions argument

My requirement is to get the chosen option and update a div. I've simulated my requirement in the code below.

I'm supposed to let user choose only the end of the months between startDate and endDate (I've done this part in the code below). But I couldn't update the with the chosen date. I could only access the "value" attribute in the Not the label or text.

http://jsfiddle.net/priyaa2002/xpcbounr/3/

<div ng-app="myApp">
<div ng-controller="DateCtrl">
<div class="edit__table__field"><p>{{myEnrollment.coverageEndDate}}</p></div>
<select ng-model="myEnrollment.coverageEndDate" ng-options="value as coverageEndDate for (value, coverageEndDate) in
terminationDates"
ng-change="newTerminationDate(myEnrollment.coverageEndDate)" >
<option value="">Select your new Termination Date</option>
</select>
</div>
</div>


JS



angular.module('myApp', [])
.controller('DateCtrl', function($scope){
$scope.myEnrollment = {
coverageStartDate: '01/01/2016',
coverageEndDate: '06/01/2016'
};

var startDate = new Date ($scope.myEnrollment.coverageStartDate);
var endDate = new Date ($scope.myEnrollment.coverageEndDate);

var startMonth = startDate.getMonth();
var endMonth = endDate.getMonth();
var year = endDate.getFullYear();

function convertDate(date) {
var parts = date.toString().split(" ");
var months = {
Jan: "01",
Feb: "02",
Mar: "03",
Apr: "04",
May: "05",
Jun: "06",
Jul: "07",
Aug: "08",
Sep: "09",
Oct: "10",
Nov: "11",
Dec: "12"
};
return months[parts[1]]+"/"+parts[2]+"/"+parts[3];
};


var pickDates = endMonth - startMonth;
$scope.terminationDates = [];
for (var i=0; i < pickDates; i++){
var lastDay = new Date(year, i + 1, 0);
var formatedDate = convertDate(lastDay);
$scope.terminationDates.push(formatedDate);
}
$scope.newTerminationDate = function(coverageDate) {
$scope.myEnrollment.coverageDate = "hello";
}

});

Answer

You can simply do:

 <select ng-model="myEnrollment.coverageEndDate" ng-options="value as value for value in terminationDates" ng-change="newTerminationDate(myEnrollment.coverageEndDate)" >
        <option value="">Select your new Termination Date</option>
 </select>

Hope it helps!