Domanda

This function limits the number of checkboxes selected by the user, but I'm having trouble getting it to work when the name attribute has square brackets (i.e. name=baz[]).

For some reason I can't get this code to work in jsfiddle, but it's based on this tutorial, which has a working demo.

function chkcontrol(j) {
    var total = 0;
    for (var i = 0; i < document.form1.baz.length; i++) {
        if (document.form1.baz[i].checked) {
            total = total + 1;
        }
        if (total > 3) {
            alert("Please select up to three choices")
            document.form1.baz[j].checked = false;
            return false;
        }
    }
}

 <form name="form1">
    <input type=checkbox name="baz[]" value="1" onclick="chkcontrol(0);">Item 1
    <input type=checkbox name="baz[]" value="2" onclick="chkcontrol(1);">Item 2
    <input type=checkbox name="baz[]" value="3" onclick="chkcontrol(2);">Item 3
    <input type=checkbox name="baz[]" value="4" onclick="chkcontrol(3);">Item 4
    <input type=checkbox name="baz[]" value="5" onclick="chkcontrol(4);">Item 5

    <input type=submit value="submit">

</form>
È stato utile?

Soluzione

Chaya, your issue is actually stemming from the fact that "[]" is part of the name.

While there are provisions to turn forms and their named elements into JS-accessible objects automatically, there are no provisions to understand which elements are intended to be arrays, versus non-arrays, as that's a server-side distinction: ?baz[]=1&baz[]=2.

If you were to ask for form1["baz[]"]; you should get a list of all elements named "baz[]".

From there, if you were to say form1["baz[]"][0]; you should get the first element named "baz[]".

You can, of course, write some parsing magic to automatically find all elements with "[]" in their names and append the "baz" as an array of the form, filled with all elements named "baz[]". And at that point you could do exactly what you were looking to do, before.

Whether or not that's overkill depends on what you're doing.

But simply writing form1["baz[]"][i] in your loop shouldn't be much more time-consuming than what you've currently got.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top