Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Nancy Melucci
PLUS
Nancy Melucci
Courses Plus Student 35,157 Points

Picking a random element from a javascript array. Printing it along with the number of elements in the array.

Going to the well a lot here. Oh well

<

The assignment is to create a to do list. Every time you add an item, the base code returns how many items are in the array. The task is to add a print out of a randomly selected item each time an item is added.

I have tried about 20 different ways to make this happen. The code works but there is a logic error. It doesn't print a random element, it prints the last one I added. I have tried at least 12 different shuffling functions and random too.

I would be grateful to know what I am missing here. Below are the js and html. I'll spare you the css. This is the latest implementation, which does what I described above. How do I make it print a random item and not tasks[0]?

// task.js
// This script manages a to-do list.

// Need a global variable:
var tasks = [];
var randomtasks = [];

function addTask() {
    'use strict';



    // Get the task:

    var task = document.getElementById('task');

    // Reference to where the output goes:
    var output = document.getElementById('output');

    // For the output:
    var message = '';

    if (task.value) {

        // Add the item to the array:
        tasks[tasks.length] = task;   
        var randomtasks = function () {
        var urgent = tasks[Math.floor(Math.random() * tasks.length)];
        return urgent;
};




        var pickatask = randomtasks();

        // Update the page:
        message = 'You have ' + tasks.length + ' task(s) in your to-do list. The most important task to accomplish is ' + pickatask.value;
        if (output.textContent !== undefined) {
            output.textContent = message;

        } else {
            output.innerText = message;
        }

    } // End of task.value IF.
    //task.clear();
    // Return false to prevent submission:
    return false;

} // End of addTask() function.

// Initial setup:
function init() {
    'use strict';
    document.getElementById('theForm').onsubmit = addTask;
} // End of init() function.
window.onload = init;
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>To-Do List</title>
    <!--[if lt IE 9]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <link rel="stylesheet" href="css/form.css">
</head>
<body>
    <!-- tasks.html -->
    <form action="#" method="post" id="theForm">
        <fieldset><legend>Enter an Item To Be Done</legend>
            <div><label for="task">Task</label><input type="text" name="task" id="task" required></div>
            <input type="submit" value="Add It!" id="submit">
      <div id="output"></div>
        </fieldset>
    </form>
    <script src="js/tasks.js"></script>
</body>
</html>
Sandro Das Neves
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Sandro Das Neves
Front End Web Development Techdegree Graduate 23,426 Points

i test you code. you don't store de value of the task field but the tag instead. you should try to use push method on you array to add the value.

I think it's ok that way. let me know if that help.

I add some comments on what I change.

// task.js
// This script manages a to-do list.

// Need a global variable:
var tasks = [];
var randomtasks = [];

function addTask() {
    'use strict';



    // Get the task:

    var task = document.getElementById('task');

    // Reference to where the output goes:
    var output = document.getElementById('output');

    // For the output:
    var message = '';

    if (task.value) {

        // Add the item to the array:
        tasks.push(task.value);     // I change the value and the way you add your task
        var randomtasks = function () {
            var urgent = tasks[Math.floor(Math.random() * tasks.length)];
            return urgent;
        };

        var pickatask = randomtasks();

        // Update the page:
        message = 'You have ' + tasks.length + ' task(s) in your to-do list. The most important task to accomplish is ' + pickatask; // and here I delete the value property that doesn't exist.
        if (output.textContent !== undefined) {
            output.textContent = message;

        } else {
            output.innerText = message;
        }

    } // End of task.value IF.
    //task.clear();
    // Return false to prevent submission:
    return false;

} // End of addTask() function.

// Initial setup:
function init() {
    'use strict';
    document.getElementById('theForm').onsubmit = addTask;
} // End of init() function.
window.onload = init;

2 Answers

Steven Parker
Steven Parker
230,274 Points

You aren't storing the values but a reference to the element itself.

Since every item in your array is a reference to the input element "task", then no matter which one you pick, the value will be the current (most recently entered) value of that element.

You can change this by storing a copy of the element in the array instead of a reference to the element:

    // Add the item to the array:
    tasks[tasks.length] = task.cloneNode();  // store a copy of the element, not a reference

You might also consider a re-work of your code to store the values themselves instead of the whole element.

Nancy Melucci
PLUS
Nancy Melucci
Courses Plus Student 35,157 Points

Thank you everyone...the assignment is due Friday night. I'll see what I can do.