Using AngularJS to prefill a HTML5 date input field with a default value

Is there a way to bind the default value generated in moment to both the date and time input fields? I have tried using ng-model and directly binding it to the value attributes, but without success. Any suggestions on how to make this work?

Edit: Additionally, how can I bind the time input field?

<body ng-app="myApp">
<div ng-controller="MyCtrl">
    <input type="date" ng-model="date" value="{{date}}">
        <p>{{date}}</p>
    <input type="time" ng-model="time" value="{{time}}">    
</div>

Check out this fiddle for reference: http://jsfiddle.net/chrisyeung/bF9Pq/

Answer №1

If you're using Google Chrome, ensure that the Date format is specified as 'yyyy-MM-dd'.

$scope.date = $filter("date")(Date.now(), 'yyyy-MM-dd');

If not set correctly, it will not function properly. You can view a functioning example here: http://jsfiddle.net/bF9Pq/4/

Answer №2

View functional example

{{newDate | date:'MM/dd/yyyy'}}

I updated the variable to newDate and included a date filter for formatting.

Answer №3

value="{{today}}" 

triggers initialization error: The entered value "{{default_date}}" is not in the required format, "yyyy-MM-dd".

resolution: avoid setting the date in the template!

<input type="date" ng-model="date_input">

set the date in the controller instead!

$scope.date_input = new Date();

Answer №4

Another way to achieve this is:

$latest.date = new Date().toLocaleDateString('en-CA');

Answer №5

Utilizing the moment library enables you to do the following:

$scope.date = new Date()

If the value is already stored in a database or variable:

$scope.date = new Date(moment(varName).tz('Asia/Kolkata').format('L'))

moment.locale();         // en
moment().format('LT');   // 9:58 AM
moment().format('LTS');  // 9:58:18 AM
moment().format('L');    // 12/07/2020
moment().format('l');    // 12/7/2020
moment().format('LL');   // December 7, 2020
moment().format('ll');   // Dec 7, 2020
moment().format('LLL');  // December 7, 2020 9:58 AM
moment().format('lll');  // Dec 7, 2020 9:58 AM
moment().format('LLLL'); // Monday, December 7, 2020 9:58 AM
moment().format('llll'); // Mon, Dec 7, 2020 9:58 AM

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

Using jQuery to animate a form submission in CodeIgniter

I have integrated two jQuery plugins into my application, which are: jQuery validate : . jQuery blockui : http://malsup.com/jquery/block/#download The application is developed using PHP Codeigniter and jQuery. It consists of a form created with the fol ...

Tips on avoiding duplicate selection of checkboxes with Vue.js

Recently delving into vue.js, I encountered a challenge with multiple checkboxes sharing the same value. This resulted in checkboxes of the same value being checked simultaneously. How can this issue be resolved? var app = new Vue({ el: '#app&apo ...

What is the best way to separate a string using a comma as a delimiter and transform it into a string that resembles an array with individual string elements

I am in search of a way to transform a string, such as: "one, two, three, four" into a string like: "["one", "two", "three", "four"]" I have been attempting to devise a solution that addresses most scenarios, but so far, I have not been successful. The ap ...

Scrolling using JavaScript's 'smooth scrolling' feature is currently disabled

Background of the Issue: I am in the process of creating a one-page website using Twitter Bootstrap 3 within an ASP.NET MVC project. The Challenge: My current challenge involves implementing 'smooth scrolling' functionality that scrolls to the ...

Is it possible for my OAuth2 callback page to share the same HTML page? Also, what is the process for obtaining the token?

In my setup, I am working with static html and javascript along with C# Web API. One of the scenarios I encountered involves a link that triggers an oauth2 server from my HTML file named index.html. The question arises: Is it appropriate to establish the c ...

Guide on adjusting the CSS styling of elements in real-time from the backend using a user customization panel to modify the appearance of various web pages

Imagine a scenario where we have a website consisting of multiple pages, including a user account page. The user has the ability to modify the color, font size, and style of certain elements on other pages for their own viewing preferences. How can this fu ...

Vue alert]: The element "options" is not declared in the current instance but is being referenced during the rendering process. Facing problem with Vue JS

Encountering an error while rendering the project. I've thoroughly checked all details but couldn't pinpoint which line is causing the issue. The console displays the following warning: Vue warn]: Property or method "options" is not defined on th ...

Implementing pagination within nested ng-repeat in Angular app

I am currently utilizing Angular along with the Material library in my project. I am facing an issue with two nested ng-repeat loops within md-tables. The problem lies in the fact that the variable is getting overridden with each request in the nested loop ...

Persistently Undefined Angular Attribute

I have been trying to dynamically bind a CSS class using an AngularJS function. While the functionality is working properly, I keep encountering numerous errors in the browser console. Can anyone offer assistance with this issue? I have included my code an ...

uWebSockets supporting multiple concurrent user sessions

To keep things simple, let's assume that my server is running just one uWebSockets instance: struct UserData { uWS::WebSocket<true, uWS::SERVER> *ws; bool logged_in = false; ID user_id; }; uWS::SSLApp() .ws<UserData>( ...

Is Immutable state considered a key functional aspect in the ReactJs framework?

One key aspect of an imperative program is the emphasis on state and its modifications. When it comes to ReactJs, there is a push for more functional programming styles, such as using purity and higher-order functions. I'm curious to explore whether ...

Angular: Disabling a button based on an empty datepicker selection

Can anyone help me figure out how to disable a button when the datepicker value is empty? I've tried using ngIf to check if the datepicker is empty and then disable the button, but it's not working. My goal is to make the button unclickable if th ...

When the label is clicked, retrieve the value of the checkbox within

I have a checkbox inside a label, and for design purposes, I added a div there. My requirement is to get the checkbox value on the click event of the label. However, I am always getting false whenever the checkbox is clicked. <label class="text-xs col- ...

When using Protractor, clicking on an element that is displayed may not work when using the `by.buttonText` locator

I recently changed my approach from locating an element by id to using button text, as I now have a single button with changing text. However, my tests are now failing. Here is the code for my button: <button type="button" class="btn btn-primary" ng-c ...

Separate a string using commas but disregard any commas inside quotation marks

Similar Question: JavaScript code for parsing CSV data There is a string that looks like this: "display, Name" <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d49584e497d49584e49135e5250">[email protected]</a> ...

Activate the button with a tap of the space bar on a webpage

Is it possible to have a button on a webpage triggered both by clicking with the mouse and hitting the spacebar? HTML <div class="col-12 button small-button"> <a onclick="generator()"> <img src="icones%20web%20projeto.p ...

Move a Java application from a trial SAP HCP to a complete SAP HCP membership

After successfully creating a Java IoT App with Raspberry Pi running on SAP HANA HCP trial account, I am now looking to enhance its functionality within the SAP HANA Development Workbench. Is there a way to import it into the SAP HANA account with ease, o ...

Headers cannot be set again after they have been sent to the client in Express Node

I attempted to create a post request for login with the following code: router.post('/login', async(req, res) =>{ const user = await User.findOne({gmail: req.body.gmail}) !user && res.status(404).json("user not matched") c ...

utilizing asynchronous functions with socket.io for optimized performance

This particular code snippet initiates the first emit to the client, which is received as the messageStart: 'Job is starting...' This part is functioning correctly. Following that, the code launches puppeteer to take a screenshot named example.pn ...

Using highlights in an external template does not function as expected

I am new to using AngularJS and I have encountered a problem. I am currently incorporating Prism.js or Highlight.js into my website (same result). It works perfectly in index.html, but it doesn't seem to work in other templates that are loaded with n ...