html - How do I write JavaScript that validates input across multiple forms? -
i attempting write javascript traverses multiple html forms, checks input given value on edit, enables/disables submit button form based on input value.
i have simple example script, overrides onclick function of checkboxes, test flow of 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 expect happen: checkboxes change value of submit button in same form.
what happens: checkboxes change value of submit button in last form.
the actual code smarter, want understand flow of javascript code before progressing onto more complex.
thanks in advance!
try this:
document.body.onchange = function(e) { // delegates way body - if have more specific // container, prefer using instead. e = e || window.event; var t = e.srcelement || e.target; if( t.nodename == "input" && t.type == "checkbox") { // may want add classname checkboxes more specificity t.parentnode.getelementsbytagname('input')[1].disabled = !t.checked; } };
the reason seeing behaviour you're getting because inputs
' value not fixed, repeatedly re-assigning next form's elements, resulting in last one.
Comments
Post a Comment