How can I disable all form elements within <div> at once?
For example:
<div id='example'>
<input type=text name='ex1'>
<input type=text name='ex2'>
<input type=text name='ex3'>
</div>
Thanks!
How can I disable all form elements within <div> at once?
For example:
<div id='example'>
<input type=text name='ex1'>
<input type=text name='ex2'>
<input type=text name='ex3'>
</div>
Thanks!
<script type="text/javascript">
function f(){
var el=document.getElementById('example');
var all=el.getElementsByTagName('input');
alert(all[0].name); // ex1
alert(all[1].name); // ex2
alert(all[2].name); // ex3
var inp, i=0;
while(inp=all[i++]) {
alert(inp.name);
inp.disabled=true;
}
}
</script>
</head>
<body>
<input type="button" value="disable all elements" onclick="f()">
<div id="example">
<input type="text" name="ex1">
<input type="text" name="ex2">
<input type="text" name="ex3">
</div>
I had to stop and think about things in the code when I saw the while loop.
Code that’s easier to read and understand is:
var el = document.getElementById('example'),
all = el.getElementsByTagName('input'),
i;
for (i = 0; i < all.length; i++) {
all[i].disabled = true;
}
It’s also a good idea to give functions meaningful names, and to not embed javascript within the html.
We can even take a leaf from best practices to speed up your web site and place the javascript at the end of the body.
<body>
<input id="disableExample" type="button" value="disable all elements">
<div id="example">
<input type="text" name="ex1">
<input type="text" name="ex2">
<input type="text" name="ex3">
</div>
<script src="script.js"> </script>
</body>
function disableInputs(el) {
var el = document.getElementById('example'),
all = el.getElementsByTagName('input'),
i;
for (i = 0; i < all.length; i++) {
all[i].disabled = true;
}
}
document.getElementById('disableExample').onclick = function () {
disableInputs('example');
}
Thank you for that resource.
pmw57
thanks for your codes and your help.
Thanks for the neat link and the code. I’ll try it out.
Would
all = el.getElementsByTagName('*')
work if I have more than one type of form element in the list?
and will this work on all browsers?
Thanks muazzez and pmw57. I tried and the code works perfectly.
It will work on most browsers except for IE7
http://ejohn.org/blog/object-getelementsbytagname-ie7-bug/
If you’re wanting to attach an event to all elements, you’re better off having only the one event at the top-level that monitors what happens below.