Neil Neil - 3 months ago 9
HTML Question

How do I add the current date of input to a dynamic list?

I want to add a date (shown also to user) to each list input of the user in the web app I am working on.

This is my HTML code

<div id="todo">
<header>
<h1>To-Do List</h1>
<input id="new-todo" type="text" placeholder="Things you need to do...">
</header>

<section id='main'>
<ul id='todo-list'></ul>
</section>
</div>


and JavaScript is here

$(document).ready(function() {
function runBind() {
$('.destroy').on('click', function(e) {
$currentListItem = $(this).closest('li');

$currentListItem.remove();
});

$('.toggle').on('click', function(e) {
var $currentListItemLabel = $(this).closest('li').find('label');

if ( $currentListItemLabel.attr('data') == 'done' ) {
$currentListItemLabel.attr('data', '');
$currentListItemLabel.css('text-decoration', 'none');
}
else {
$currentListItemLabel.attr('data', 'done');
$currentListItemLabel.css('text-decoration', 'line-through');
}
});
}

$todoList = $('#todo-list');
$('#new-todo').keypress(function(e) {
if (e.which === EnterKey) {
$('.destroy').off('click');
$('.toggle').off('click');
var todos = $todoList.html();
todos += ""+
"<li>" +
"<div class='view'>" +
"<input class='toggle' type='checkbox'>" +
"<label data=''>" + " " + $('#new-todo').val() + "</label>" +
"<a class='destroy'></a>" +
"</div>" +
"</li>";

$(this).val('');
$todoList.html(todos);
runBind();
$('#main').show();

}});
});


What should I add in the code to make that happen?
Thank you.

Answer

As was suggested, get the current date using new Date and then you can use any one of the date formatting functions (or make your own):

  • toString() gives Tue Aug 16 2016 00:05:20 GMT-0400 (Eastern Daylight Time)
  • toDateString() gives Tue Aug 16 2016
  • toLocaleDateString() gives 8/16/2016
  • You can also use .getDate(), .getMonth(), .getYear(), etc.

I would also recommend using jQuery to create your list item rather than raw HTML. You will run into issues the way you are currently doing it if you have a <, for example, in your todo name because it isn't escaped.

"<li>" +
"<div class='view'>" +
"<input class='toggle' type='checkbox'>" +
"<label data=''>" + " " + $('#new-todo').val() + "</label>" +
"<a class='destroy'></a>" +
"</div>" +
"</li>"

can be turned into

$('<li>').append(
  $('<div>').addClass('view').append(
    $('<input>').addClass('toggle').attr('type', 'checkbox')
  ).append(
    $('<label>').attr('data', '').text($('#new-todo').val())
  ).append(
    $('<a>').addClass('destroy')
  )
)
Comments