0

Im writing a program that creates a cookie with a string of foods in it. Upon pressing submit, whichever foods have been checkbox'd should be collected into a string and then recorded into the document's cookie. Then an alert() displays my cookie for debugging purposes.

I am having trouble getting my html button to successfully invoke my submit() function. When I press submit, all code within the script tags execute EXCEPT for my submit function. I tried reordering my script code but that didnt help.

My program has behaved the same in different doctypes, ide's, and browsers so i know its not an environment issue.

    <body>
    <div>
        <form>
            Select your foods.<br>
            <input type="checkbox" name="foods" id="pine">Pine<br>
            <input type="checkbox" name="foods" id="tuna">Tuna<br>
            <input type="checkbox" name="foods" id="bread">Bread<br>
            <input type="checkbox" name="foods" id="apple">Apple<br>
            <input type="checkbox" name="foods" id="oats">Oats<br><br>
            <button type="button" onclick="submit()">Submit</button>
        </form>                
    </div>
    <script>

    var pine = document.getElementById("pine");
    var tuna = document.getElementById("tuna");
    var bread = document.getElementById("bread");
    var apple = document.getElementById("apple");
    var oats = document.getElementById("oats");

    var foods = [pine,tuna,bread,apple,oats];

    function submit()
    {

        var collection = "";
        for (i=0;i<foods.length;i++)
        {
            if (foods[i].checked)
            {
                collection += foods[i].id + " ";
            }
        }

        document.cookie = collection;
        alert(document.cookie);

    }


    </script>
</body>

Thanks so much in advance guys!

2 Answers2

1

That's because submit is a reserved word in JavaScript. Use another function name, for example submitItem(). Also note that by default a button can submit a form, in which does not seem to be your intention. I would recommend placing it outside the form or preventing it's default behavior.

Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
1

submit() is an implementation-dependent reserved word and should not be used as a function name (http://www.javascripter.net/faq/reserved.htm, http://www.w3schools.com/js/js_reserved.asp) . Just change the function name, it should work.

Please check this plunkr

Tharaka
  • 2,355
  • 1
  • 20
  • 22