Asked in Box onsite interview. With a node.js server on backend.
$().ready(function() {
$('#add').on('click', addTask);
$('#tasks').on('click', markComplete);
// Alternative way
// var tasksElement = document.getElementById('tasks');
// tasksElement.addEventListener('click', markComplete);
//document.getElementById('task-input').onkeydown = function(e){
$('#task-input').on('keydown', function(e) {
if(e && e.keyCode == 13){
addTask();
}
});
function renderTask(result) {
var checkboxContainerId = 'check' + result.id;
var taskTextId = 'tasktext-' + result.id;
if (result.done == '1') {
checkedState = ' checked ';
} else {
checkedState = '';
}
taskHtml = '
';
taskHtml += '';
taskHtml += '' + result.data + '';
$('#tasks').append(taskHtml);
}
function taskAdded(result) {
renderTask(result);
$('#task-input').val('');
}
function renderResults(results) {
results.forEach(renderTask);
}
function addTask(e) {
url = 'http://localhost:9898/todo/tasks/create';
inputData = $('#task-input').val();
if (!inputData) {
return;
}
$.ajax({
url: url,
type: "POST",
data: {data: inputData} ,
success: taskAdded,
});
}
function markComplete(e) {
var done;
if (e.target && e.target.matches("input.task-checkbox")) {
var taskId = $(e.target).attr('task-id');
if ($(e.target).is(":checked")) {
done = "1";
} else {
done = "-1";
}
var editUrl = 'http://localhost:9898/todo/tasks/' + taskId + '/edit';
$.ajax({
url: editUrl,
type: "POST",
data: {done: done},
success: function(result) {
}
});
}
}
var getTasksUrl = 'http://localhost:9898/todo/tasks';
$.ajax({
url: getTasksUrl,
type: "GET",
success: renderResults,
});
}
);