Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

dbrink dbrink
dbrink dbrink
6,258 Points

Trying to make a more complicated version of the variable challenge

Hey guys,

I've decided to run through the earlier Javascript challenges and try to complete them in a more DOM related way.

I'm using forms with the variable challenge and trying to loop through them and apply their values as arguments in a function that will build and concatenate my story.

At the moment, only the first input value from my loop is applied. I remember reading about why this is happening, but I can't recall and I can't figure out how to change this.

Anyone have a moment to help me out?

https://jsfiddle.net/8fgpnqcv/4/

1 Answer

Steven Parker
Steven Parker
220,415 Points

:point_right: It looks like you have two issues here:

You defined makeStory to take 5 arguments, but each time you call it, you pass is just one argument.

Also, the entire contents of the result div is replaced each pass through the loop, so only what the last pass produces will be seen.

So the end result is you see only the final input, but where the first one should be. All other positions are undefined.

One way to fix it would be to modify placeStory like this:

    placeStory: function place(e) {
        e.preventDefault();
        filledOut = true;
        for (var i = 0; i < 5; i++) {
            if (!selectors.inputs[i].value) {
                filledOut = false;
                break;
            }
        }
        if (filledOut) {
            selectors.div.innerHTML = control.makeStory(
                selectors.inputs[0].value,
                selectors.inputs[1].value,
                selectors.inputs[2].value,
                selectors.inputs[3].value,
                selectors.inputs[4].value);
        } else {
            selectors.div.innerHTML = 'Fill out all inputs first.';
        }
    }
dbrink dbrink
dbrink dbrink
6,258 Points

That definitely resolved the issue. Thanks for another helpful response.

In this scenario, would it have just been better to declare each input separately? I was trying to be at least somewhat elegant by looping over all inputs, but it seems to have backfired.