Question

Can someone explain why this for...loop doesn't work? (it should write all checked checkboxes but it writes only the last checked)

function Matula() 
{
    var x = document.getElementsByTagName("body")[0];
    var y = document.createElement("p");
    var g = document.createTextNode("Vasa pizza bude obsahovat:");
    y.appendChild(g);
    x.appendChild(y);
    var swag = document.forms["lol"].matej.length;
    for (var i = 0; i < swag; i++) 
    {
        if (document.forms["lol"].matej[i].checked) 
        {
            var torko = document.getElementsByTagName("body")[0];
            var q = document.createElement("p");
            var w = document.createTextNode(document.forms["lol"].matej[i].value);
            q.appendChild(w);

            torko.appendChild(q);
            return mocny = 0
        }
    };
}

No correct solution

OTHER TIPS

return mocny = 0

exits the function , so for it loops only once, put it outside for loop

There is a return statement in your if block. This will essentially break the loop after the first time it goes inside the if. So that means only value of one check box will be print out.

I have no idea as to what that is supposed to do as it is awfuly confusing will all those var names. But your return inside your if, which inside your for loop, doesn't seem right.

You should put that at the last line of your function.

A cleaner code could look like this:

function Matula() {
    var body = document.body;
    addParagraph(body, "Vasa pizza bude obsahovat:");

    var allToppings = document.forms["lol"].matej;
    var toppingsCount = allToppings.length;
    for (var i = 0; i < toppingsCount; i++) {
        if (allToppings[i].checked) {
            addParagraph(body,allToppings[i].value);
        }
    }
}

function addParagraph(body, textToAdd) {
    var p = document.createElement("p");
    p.appendChild(textToAdd);
    body.appendChild(y);
}

Typed off my head, might contain typos
Makes it so much easier to read. Btw. Bracket position does make a difference (it isn't Java), so keep it on the same line (Google the reasons) Does it work for you?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top