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

Js Cookies - Using indexOf to find "=" and it is returning -1.

This is for a class assignment. I'm supposed to be able to extract my user name from the prompt dialogue box using the indexOf(method??). It will return "Greetings, " but no name. It is saying that the index is -1 so it doesn't exist right? Am I not referring to the prompt correctly in my cookie? I have tinkered with it all morning but I can't seem to figure it out

<!doctype html>
<html>
<head>

<title>Cookies</title>
<script>
window.onload=setCookie;
function setCookie() {
    var user_name = prompt("Please enter your user name");
        alert(user_name);
    document.cookie="Name="+user_name;
    NameStart = document.cookie.indexOf("=");
    alert(NameStart);

    document.getElementById('msg').innerHTML = "Greetings, " + document.cookie.substring(NameStart + 1);
}
</script>
</head>
<body>
<h1 id="msg"></h1>
</body>

1 Answer

Hey Kirstine,

In order to set cookies, you have to be running in a server environment. Your code works as expected but not until you run it with a server. Is your challenge to just get your name from the prompt box or is it to set a cookie as well?

If have to use cookies, you can use some local server software such as XAMPP to test your code out or if you have a remote hosting server, you can upload your HTML file there.