Establishing a pre-selected option in a drop-down menu

I am working on a dropdown list and my goal is to have the default option selected when the page loads

<b>Filter Within Months:</b>
<select  class="btn green" ng-model="myOptions" ng-options="i.label for i in items track by i.id" ng-change="selectedItemChanged()">
</select>

In the controller.js file, I am setting the model to "Default" on load.

$scope.myOptions.id = 0;
$scope.items = [{
  id: 0,
  label: 'Default'
}, {
  id: 1,
  label: 'All'
}, {
  id: 2,
  label: '3 month'
}, {
  id: 3,
  label: '6 month'
}, {
  id: 4,
  label: 'Previous Month'
}];

$scope.selectedItemChanged = function() {
  var date = new Date();
  var endDate = Date.now();
  var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
  var firstDayOfPreviousMonth = new Date(date.getFullYear(), date.getMonth() - 1, 1)
  var lastDayOfPreviousMonth = new Date(date.getFullYear(), date.getMonth(), 0)

  if ($scope.myOptions.id === 1) { //show All
    startDate = null;
  } else if ($scope.myOptions.id === 2) { //show 3 month
    startDate = date.setDate(date.getDate() - 90);
  } else if ($scope.myOptions.id === 3) { //show 6 month
    startDate = date.setDate(date.getDate() - 180);
  } else if ($scope.myOptions.id === 4) { //show Previous Month
    startDate = Date.parse(firstDayOfPreviousMonth);
    endDate = Date.parse(lastDayOfPreviousMonth);
  } else { //Default
    startDate = Date.parse(firstDay)
  }
  $scope.selectedDateFilterRange();
}

$scope.selectedDateFilterRange = function() {
  //filter the data
}

However, I am encountering an error when running the code

TypeError: Cannot set property 'id' of undefined at $scope.myOptions.id = 0;

Answer №1

An attempt to assign a value to a property of an undefined object is causing an issue: There is no existing object named myOptions.

Modify $scope.myOptions.id = 0;

To:

$scope.myOptions = { "id": 0 };
// Alternatively, $scope.myOptions = {};
//    $scope.myOptions.id = 0;

See the live demo

Answer №2

Give this a shot

const index = $scope.items.findIndex(item => item.id === 0);
$scope.mySelection = $scope.items[index];

Keep in mind: Using pure javascript instead of underscore.js, you can find the index of the item with id = 0 in $scope.items

Answer №3

  1. $("#selectMenu").prop("selectedIndex", 0);

  2. document.getElementById("#selectMenu").selectedIndex = 0

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

What is the most efficient way to retrieve the current user's ID within Loopback?

Given the instability and deprecation of loopback.getCurrentContext(), what strategies can I use to accurately identify users when they interact with API endpoints? Is it feasible to include the token ID in the request payload for verification purposes? H ...

What are the best practices for effectively managing jQuery UI sliders?

I am currently developing a web application that involves updating jQuery UI sliders using JavaScript. While I have managed to resolve most of the issues related to updating the slider after initialization, there is one particular issue that remains unreso ...

Using jQuery, how can you make fixed elements fade as the page scrolls?

How can I make a fixed element, such as a corner ad or notice, fade when the page is scrolled down to a certain point? What would be the most effective method for determining this point: using pixels, percentage, or another way? And how can I implement th ...

Exploring the process of iterating through a JSON response in PHP to extract all values

{ "ver":2, "inputs":[ { "sequence":4294967295, "witness":"", "prev_out":{ "spent":true, "tx_index":372805487, "type":0, "addr":"3AFgA1pHKrk4jFHwzUL1CKgZvXyFSWZfgD", "value":12712, ...

The callback function is not being executed in the Ajax request

$(document).ready(function(){ var requestURL = 'http://www.football-data.org/soccerseasons?callback=?'; $.ajax({ type: 'GET', dataType: 'json', url: requestURL, success: function(data){ cons ...

Filtering JSON data with JavaScript

Looking to group data in AngularJS using UnderscoreJS. Here is the JSON data: data = [ { "Building*": "Building A", "Wing*": "Wing C", "Floor*": "Floor 3", "Room Name*": "Room 3", "Room Type*": ...

Unable to incorporate node-vibrant into Angular 7 project

Currently facing some challenges while attempting to integrate node-vibrant into my Angular 7 project: -Successfully imported with import * as Vibrant from 'node-vibrant';, but encountering a warning in VS Code: Module '"/Users/xxxx/Docume ...

JS selection-dropbox

As someone who is relatively new to JS, I am struggling a bit. The goal of the code is to display items with specific content (ALL, A, B, C). While the code works fine with buttons, I can't seem to get it to work with a 'Dropdown-select', ...

How can I align the Socket.io path on the client with the directory structure of my Node.js server?

Currently, I am utilizing socket.io with node.js along with Expressjs. As I serve my HTML page, I have the socket.io.js file linked directly in a script tag: <script src="/socket.io/socket.io.js"></script> I'm facing some difficulty match ...

Does an async function get automatically awaited if called in a constructor?

I am currently working on updating some code due to a library upgrade that requires it to be made async. The code in question has a base class that is inherited by other classes, and I need to call some functions in the constructor that are now asynchronou ...

Prevent premature termination of slow HTTP requests in Node.js/Express server

Having an issue with long duration http requests in my React/Nodejs application. Whenever a request takes more than 4 minutes to respond, it gets aborted before reaching the client. Could there be a timeout setting for requests or something else I am overl ...

Is there a method to initiate a 'simple' action when dispatching an action in ngrx?

Here's the scenario I'm facing: When any of the actions listed below are dispatched, I need to update the saving property in the reducer to true. However, currently, I am not handling these actions in the reducer; instead, I handle them in my ef ...

What is the best way to calculate the number of days that have passed since a certain

Hey there, I've got this 10 Dec, 2019T14:07:21 date format from the backend. My goal is to determine how many days ago it was. For example, today is the 20th, so if the date is today's date, it should show as 0 days ago. ...

Is it within the realm of possibility for a route-handling function to accept more than two parameters?

Recently, I started learning about node js and delved into the world of jwt authentication. While going through some code snippets, I came across a request handler in express that caught my attention. app.post('/login',function(req,res){...}); ...

Code - Capture user's input

I have multiple input fields in my HTML document and I want to retrieve the text entered into one of them. Here's an example of one such input field: <TH> <FORM> <input name="designation" type="text" size="12" /> < ...

Adjust the size of the sliding tool with images of varying dimensions

My mobile-first slider features three different types of images: tall, horizontally long, and square. I want the size of the slider to be determined by the horizontally long image and then scale and center the other images to fit its size. To achieve this, ...

Comparing Express.js View Engine to Manual Compilation

Currently, I am utilizing Express.js along with the hbs library to incorporate Handlebars templates in my application. Lately, I've delved into establishing a build system using gulp for my app and stumbled upon packages like gulp-handlebars. My query ...

A guide on how to reset Orbit Controls once the target has been defined

After clicking the mouse, I successfully set a new target for my THREE.OrbitControls and it works perfectly. However, once the camera pans to the new location, I lose all mouse interaction. I suspect that I may have broken the controls when I made the came ...

Choose a file from Safari browser using Protractor

Running this code in Safari does not produce the desired result, however it functions correctly in both Chrome and Firefox: var pathToFile = path.resolve('./scripts', file); element( by.css('input[ng-file-select="onFileSelect($files)"]&apos ...

Set a variable in Node.js to capture the return value of res.json

Embarking on the creation of a social network using Node.js, I must admit that I am quite new to this field. This marks my inaugural post on the subject and I sincerely hope for your understanding. Within my social network project, I aim to implement an a ...