Angular JS problem with loading year, date, and day in a drop-down menu

I am attempting to use Angular JS to load day, year, and month. I am currently facing two issues. Firstly, I need to include a "--select--" option in all of my dropdowns. Additionally, the month name should be displayed in the dropdown without the corresponding number. How can I make these adjustments?

 <div>
  Year : <select ng-model="SelectedYear" ng-options="label for label in Years" ng-change="UpdateNumberOfDays()"></select>
</div>
<div>
  Month: <select ng-model="SelectedMonth" ng-options="label for label in Months" ng-change="UpdateNumberOfDays()"></select>
</div>
<div>
  Day: <select ng-model="SelectedDay" ng-options="label for label in Days | limitTo:NumberOfDays"></select>
</div>

Kindly review my demo

Demo

Answer №1

There are two things that need to be changed in your code: in your script.js

var months = $.map($(Array('jan','feb' , 'mar' ,'apr' ,'may','june','jul','Aug','Sept','Oct','Nov','Dec')), function (val, i) { return val; });

Prior to this change, you were using 12 arrays and simply returning the index.

Additionally, add

<option value="">-- choose State --</option></select>
inside the Select tag.

// Custom code snippet

(function () {
    var myApp = angular.module('MyApp', []);

    myApp.controller('BirthdayController', ['$scope', function ($scope) {

        var numberOfYears = (new Date()).getYear() - 10;
        var years = $.map($(Array(numberOfYears)), function (val, i) { return i + 1900; });
        var months = $.map($(Array('jan','feb' , 'mar' ,'apr' ,'may','june','jul','Aug','Sept','Oct','Nov','Dec')), function (val, i) { return val; });
        var days = $.map($(Array(31)), function (val, i) { return i + 1; });

        var isLeapYear = function () {
            var year = $scope.SelectedYear || 0;
            return ((year % 400 === 0 || year % 100 !== 0) && (year % 4 === 0)) ? 1 : 0;
        }

        var getNumberOfDaysInMonth = function () {
            var selectedMonth = $scope.SelectedMonth || 0;
            return 31 - ((selectedMonth === 2) ? (3 - isLeapYear()) : ((selectedMonth - 1) % 7 % 2));
        }

        $scope.UpdateNumberOfDays = function () {
            $scope.NumberOfDays = getNumberOfDaysInMonth();
        }

        $scope.NumberOfDays = 31;
        $scope.Years = years;
        $scope.Days = days;
        $scope.Months = months;
    }]);
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@*" data-semver="1.4.0-beta.5" src="https://code.angularjs.org/1.4.0-beta.5/angular.js"></script>
  <script data-require="jquery@*" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-app="MyApp">
  <div class="ng-scope" ng-controller="BirthdayController">
    <h1>Birthday Validator</h1>
    <div>
      Year : <select ng-model="SelectedYear" ng-options="label for label in Years" ng-change="UpdateNumberOfDays()">
        <option value="">-- choose Year --</option>
        </select>
    </div>
    <div>
      Month: <select ng-model="SelectedMonth" ng-options="label for label in Months" ng-change="UpdateNumberOfDays()">
        <option value="">-- choose Month --</option></select>
    </div>
    <div>
      Day: <select ng-model="SelectedDay" ng-options="label for label in Days | limitTo:NumberOfDays">
        <option value="">-- choose Day --</option></select>
    </div>
  </div>
</body>

</html>

Answer №2

If you want to include the default option --select--, follow these steps. When this option is chosen, the ngModel value will be set to '':

Month: <select ng-model="SelectedMonth" ng-options="label for label in Months" ng-change="UpdateNumberOfDays()">
        <option value=""> --select-- </option>
      </select>

For heavy date operations, consider using a library like momentjs.

Import

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>

script.js

$scope.Months = moment.months(); // Eliminate current logic for calculating month array.
// This function provides a direct list of all month names.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Prevent selection based on JSON information

I am utilizing the Jiren filter library to sort through JSON data. If a particular filter criteria does not match any of the results, I would like to disable that option in the select dropdown. For instance, if "Silversea Expedition" is not found in my re ...

Customize menu items in Angular ui-grid when right clicking on a cell

Seeking help with Angular UI-grid for a specific feature needed: I want to display a custom menu when a user right-clicks on a specific 'CELL/Column' in the grid, such as 'B' in the example image below. When the user right-clicks, the ...

Issues arise when attempting to extract data from a data provider using JSON within the context of the Ionic framework

Hey there! I'm relatively new to the world of Angular and Ionic, and I've embarked on a project to create a pokedex app. My approach involves using a JSON file containing an array of "pocket monsters". However, my current challenge lies in extrac ...

The ASP.NET MVC3 form collection registers as 0 when performing a jQuery ajax post

I'm currently developing a project on ASP.NET MVC3. My current challenge involves POSTing to a method that should return a set of data using the jQuery.ajax api. However, upon handling the request on the server, I noticed that the form collection&apo ...

Template for event cell details in Angular2 calendar view

Currently utilizing [angular-calendar] from github.com/mattlewis92/angular-calendar . My goal is to incorporate my own template as a detailed view for events. I am aiming to achieve a similar effect as shown in the image: final effect So far, I ha ...

The React component does not display text when the object is empty

I have a react component that utilizes a method to extract data from an object and display its status on another component. The issue arises when the application is loading initially; the object's length is 0. Once the data is loaded, the object&apos ...

Using Typescript with d3 Library in Power BI

Creating d3.axis() or any other d3 object in typescript for a Power BI custom visual and ensuring it displays on the screen - how can this be achieved? ...

What is the best way to ensure that a server response is received before initiating an Apollo Graph QL Query

Is there a way to call a Graph QL Query after data is received from the useEffect hook? The challenge I am facing is that hooks cannot be called conditionally. If I remove the condition, loadedAnime will become undefined. How can I overcome this limitati ...

Exploring the dynamic duo of MongoDB and GridFS

We currently manage a large-scale project that accommodates thousands of users daily. Our database system is MySQL, but we are considering transitioning to MongoDB along with GridFS. Is it feasible to utilize MongoDB and GridFS for projects on this scale? ...

What's the best way to display a bootstrap modal window popup without redirecting to a new page?

I am having trouble implementing a modal window that will display validation errors to the user when they submit a form. Currently, the window is opening as a new view instead of overlapping the existing form's view. How can I adjust my code so that t ...

Does aoMap function exclusively with THREE.BufferGeometry?

Can you provide guidance on setting up an aoMap for a standard THREE.Geometry object? Is there a demo available to reference? var uvCoordinates = geometry.attributes.uv.array; geometry.addAttribute('uv2', new THREE.BufferAttribute(uvCoordina ...

Is it possible to utilize AngularJS's $q functionality outside of an Angular component?

I am currently working on a browser application, where I have a specific file responsible for creating and initializing an object. This file is written in plain Javascript rather than being part of the Angular ecosystem like the rest of the app, which is b ...

Returning false will not terminate the each loop in cypress testing

Here is the code snippet I am working with: cy.get('[data-testid="userRecords"]') .each((record) => { if (record.find('[data-testid="delete"]').is(":enabled")) { cy.wrap(record).find(& ...

Prevent user control postback from occurring when JavaScript is active

I have been on a mission to find a solution to this issue. Hopefully, someone in this community can shed some light on it! I developed a usercontrol that utilizes .NET web controls, but I want to enhance the user experience by avoiding full postbacks. As ...

Troubleshooting: AngularJS route provider fails to load templateUrl

Currently, I am diving into the world of AngularJS and as I grasp new concepts, I am eagerly trying to implement them. My current focus lies on understanding the routeProvider functionality. Despite my efforts to include what I have learned, for some reas ...

Resolving the Challenge of Duplicate Post Requests in Rails 3 Using Ajax

Help! My Ajax is triggering twice when I only want it to happen once. I have a feeling it might be due to a double render issue, but I'm new to Rails and could really use some guidance on where to look for a solution. Here's the JS: $("select[n ...

Guide to developing a form builder web application similar to Wufoo using JQuery and Rails!

Seeking guidance on incorporating a builder similar to Wufoo into a Rails 3 application with JQuery for client-side functionality. The goal is to enable users to create something (such as a form like in Wufoo) in offline mode and then save all edits to the ...

Is it possible to utilize various providers in Next-Auth while still maintaining the same email address?

I am currently developing a Next.js application using NextAuth. At the moment, I have implemented login functionality with Google, credentials, and GitHub. However, I encountered an issue where if a user logs in with Google using the email "[email pro ...

Can a specific section of an array be mapped using Array.map()?

Currently, I am working on a project utilizing React.js as the front-end framework. There is a page where I am showcasing a complete data set to the user. The data set is stored in an Array consisting of JSON objects. To present this data to the user, I am ...

Display a toasted notification following a refresh

After reloading the page, I want to display a toast notification confirming that the file has been uploaded. Here is my current code: _fileUploads.delete = function(reload_on_return) { var filtered = root.fileUploads().filter(_ => _._id() == _fileUpl ...