mardi 20 octobre 2015

Storing checkbox tag values to an Javascript Object and String value via JSON

I'm probably making some rookie mistakes, but my brain is drained trying to figure out where I went wrong. I have an HTML form, and I need to store JUST the values of the checked selections in an script object (if it's deselected, it should be removed from the object), as well as convert the object into a string. Problem is, I haven't ever had to mix checkboxes with Javascript, and I'm completely lost. When I debug, it completely ignores the function. Any help would be greatly appreciated.

HTML for the form:

    <form method="post" action="http://ift.tt/1H69Y8T">
                <div id="errorText"></div>
                <fieldset id="faq">
                <label for="uname">Name:</label>
                <input type="text" name="uname" id="uname" required="required">
                <label for="email">E-mail:</label>
                <input type="text" name="email" id="email" required="required">
                <label for="nature" required="required">Nature of your question:</label>
                <input type="checkbox" name="nature" id="A" value="A">Option A
                <input type="checkbox" name="nature" id="B" value="B">Option B
                <input type="checkbox" name="nature" id="C" value="C">Option C</br>
                <input type="checkbox" name="nature" id="D" value="D">Option D
                <input type="checkbox" name="nature" id="other" value="other">Other
                <label for="question">Question(s):</label>
                <textarea name="question" id="question" rows="10" cols="50" required="required">
                </textarea>
                </fieldset><p>
                <input id="submit" type="submit" value="Submit">
            </form><p>

And here's the Javascript:

"use strict";

var natureObject = new Object();
var natureSubmission = "";
function checkboxObject() {
    var checkedBoxes = document.getElementsByTagName("nature").checked;
    natureObject = {};
    for (var i = 0; i < checkedBoxes.length; i++) {
        if (checkedBoxes[i].checked) {
            natureObject[fields[i].name] = checkboxObject[i].id;
        }
    }
}

function createString() {
    natureSubmission = JSON.stringify(natureObject);
}

/* create event listeners */
function createEventListeners() {
    var box = document.getElementById("nature").checked;
    if (box.addEventListener) {
        box.addEventListener("change", checkboxObject, false);
    } else if (box.attachEvent) {
        box.attachEvent("onchange", checkboxObject);
    }
}

if (window.addEventListener) {
    window.addEventListener("load", createEventListeners, false);
} else if (window.attachEvent) {
    window.attachEvent("onload", createEventListeners);
}




Aucun commentaire:

Enregistrer un commentaire