0

I am attempting to write JavaScript that traverses multiple HTML forms, checks an input for a given value on edit, then enables/disables the submit button for that form based on the input value.

I have a very simple example script, which overrides the onclick function of checkboxes, to test the flow of my code.

<form>
    <input type="checkbox" />
    <input type="submit" disabled="disabled" />
</form>
<form>
    <input type="checkbox" />
    <input type="submit" disabled="disabled" />
</form>
<form>
    <input type="checkbox" />
    <input type="submit" disabled="disabled" />
</form>
<form>
    <input type="checkbox" />
    <input type="submit" disabled="disabled" />
</form>
<form>
    <input type="checkbox" />
    <input type="submit" disabled="disabled" />
</form>
<script type="text/javascript">
    forms = document.getElementsByTagName("form");
    for(i=0; i<forms.length; i++)
    {
        inputs = forms.item(i).getElementsByTagName("input");
        inputs.item(0).onclick = function()
        {
            if(this.checked)
                inputs.item(1).removeAttribute("disabled");
            else
                inputs.item(1).setAttribute("disabled","disabled");
        }
    }
</script>

What I expect to happen: the checkboxes change the value of the submit button in the same form.

What actually happens: all the checkboxes change the value of the submit button in the last form.

The actual code will be somewhat smarter, but I want to understand the flow of JavaScript code before progressing onto something more complex.

Thanks in advance!

1 Answer 1

2

Try something like this:

document.body.onchange = function(e) {
    // this delegates all the way to the body - if you have a more specific
    // container, prefer using that instead.
    e = e || window.event;
    var t = e.srcElement || e.target;
    if( t.nodeName == "INPUT" && t.type == "checkbox") {
        // may want to add a className to the checkboxes for more specificity
        t.parentNode.getElementsByTagName('input')[1].disabled = !t.checked;
    }
};

The reason you are seeing the behaviour you're getting is because inputs' value is not fixed, you are repeatedly re-assigning it to the next form's elements, ultimately resulting in the last one.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.