checkbox - Javascript position of onchange assignment -
i have checkbox , text input. want text input enabled if checkbox checked. found answer problem here, following code did not work:
<!doctype html public "-//w3c//dtd html 4.01//en" "http://www.w3.org/tr/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>title</title> <script type="text/javascript"> document.getelementbyid('yourbox').onchange = function() { document.getelementbyid('yourtext').disabled = !this.checked; }; </script> </head> <body> <input type="text" id="yourtext" disabled /> <input type="checkbox" id="yourbox" /> </body> </html>
however, noticed code works if move < script > environment below < input > boxes that
<!doctype html public "-//w3c//dtd html 4.01//en" "http://www.w3.org/tr/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>title</title> </head> <body> <input type="text" id="yourtext" disabled /> <input type="checkbox" id="yourbox" /> <script type="text/javascript"> document.getelementbyid('yourbox').onchange = function() { document.getelementbyid('yourtext').disabled = !this.checked; }; </script> </body> </html>
why position of < script > environment play role onchange attribute?
that's because page parsed top, , each element added parsed.
when script
tag has been parsed code run right away. @ time input
tags hasn't been parsed, input
elements doesn't exist yet.
by placing script
tag below input
tags, script runs after input
elements has been created.
instead of rearranging code, can use onload
event make sure code runs after page parsed:
<!doctype html public "-//w3c//dtd html 4.01//en" "http://www.w3.org/tr/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>title</title> <script type="text/javascript"> window.onload = function() { document.getelementbyid('yourbox').onchange = function() { document.getelementbyid('yourtext').disabled = !this.checked; }; }; </script> </head> <body> <input type="text" id="yourtext" disabled /> <input type="checkbox" id="yourbox" /> </body> </html>
Comments
Post a Comment