Matthew Kelsay Matthew Kelsay - 6 months ago 10
HTML Question

To Do List in JavaScript/HTML

I have set up this To Do List and almost everything is working perfect. However, if I delete everything in the list. It won't let me add a new entry and I can't seem to figure it out why. It will work fine as long as I have at least one entry on the list.

Any help is much appreciated thank you.



< head >
< script type = "text/javascript" >
/*<![CDATA[*/
function addTask() {
if (document.forms[0].newtask.value == "")
window.alert("You must enter a value in the New Task field.");
else {
if (document.forms[0].tasks.options[0].value == "tasks")
document.forms[0].tasks.options[0] = null;
var newTask = new Option();
newTask.value = document.forms[0].newtask.value;
newTask.text = document.forms[0].newtask.value;
var numTasks = document.forms[0].tasks.options.length;
document.forms[0].tasks.options[numTasks] = newTask;
document.forms[0].newtask.value = "";
}
}

function deleteTask() {
var selectedTask = 0;
var taskSelected = false;
while (selectedTask < document.forms[0].tasks.length) {
if (document.forms[0].tasks.options[selectedTask].selected == true) {
taskSelected = true;
break;
}
++selectedTask;
}
if (taskSelected == true)
document.forms[0].tasks.options[selectedTask] = null;
else
window.alert("You must select a task in the list.");
}

function ascendingSort() {
var newTasks = new Array();
for (var i = 0; i < document.forms[0].tasks.length; ++i) {
newTasks[i] = document.forms[0].tasks.options[i].value;
}
newTasks.sort();
for (var j = 0; j < document.forms[0].tasks.length; ++j) {
document.forms[0].tasks.options[j].value = newTasks[j];
document.forms[0].tasks.options[j].text = newTasks[j];
}
}

/*]]>*/
< /script>

<title>To Do List</title >
< /head>

<body>
<h1>To Do List</h1>
<form action="">
<p>New Task
<input type="text" size="68" name="newtask" />
</p>
<p>
<input type="button" value="Add Task" onclick="addTask()" style="width: 150px" />
<input type="button" value="Delete Selected Task" onclick="deleteTask()" style="width: 150px" />
<br />
<input type="button" value="Ascending Sort" onclick="ascendingSort()" style="width: 150px" />
</p>
<p>
<select name="tasks" size="10" style="width: 500px">
<option value="tasks">Tasks</option>
</select>
</p>
</form>
</body>




Answer

When you delete all your tasks you are having an empty select, with no options.

You need to guard your condition in your addTask function with

document.forms[0].tasks.options.length > 0

Something like this:

if (document.forms[0].tasks.options.length > 0 && document.forms[0].tasks.options[0].value == "tasks")
    document.forms[0].tasks.options[0] = null;

See code updated

Comments