gr*********@gmail.com said on 17/03/2006 1:44 PM AEST:
i want to call a javascript for onclick action on all the checkboxes on
my form.
I know that i can individually call the script for each checkbox
onclick.
I was wondering if there was any better solution.
If you want to cut down on the amount of HTML you have to send, then
attach the events using script. Then they will only be attached if the
browser supports scripting and your HTML stays cleaner.
Sample:
<form name="formA" action="">
<p>
<label for="CB1"><input type="checkbox"
id="CB1" name="CB1">CB 1</label><br>
<label for="CB2"><input type="checkbox"
id="CB2" name="CB2">CB 2</label><br>
<label for="CB3"><input type="checkbox"
id="CB3" name="CB3">CB 3</label><br>
<input type="reset">
</p>
</form>
<div id="msg">message here...</div>
<script type="text/javascript">
function addClick(fName, elType, clickFn)
{
var form = document.forms[fName];
var els;
if (form && (els = form.elements)){
for (var i=0, len=els.length; i<len; ++i){
if (els[i].type == elType){
els[i].onclick = clickFn;
}
}
}
}
function showName()
{
var el = this;
var elDiv = document.getElementById('msg');
if ( elDiv && el && el.name){
elDiv.innerHTML = el.name + ': '
+ ((el.checked)?'checked':'un–checked');
}
}
addClick('formA', 'checkbox', showName)
</script>
--
Rob