Forum Moderators: open

Message Too Old, No Replies

Getting Error While Checking CheckBox

         

srins

7:23 pm on Dec 4, 2006 (gmt 0)

10+ Year Member



Hi,

I tried to use one javascript function to check all check boxes when i check "All" Checkbox.

And if i select particular Checkbox,it will uncheck "All" and Check that Selected particular Checkbox.

<code>

<body onload="init()" topmargin=0>
<html:form method="post" action="testCaseAdd.do">
<input type="checkbox" name="All" value="All" onClick="CheckUncheck()">All
<input type="checkbox" name="capability" show="Default" onClick=" UncheckAll()" value="default" >Default
<input type="checkbox" name="capability" show="template" onClick=" UncheckAll()" value="default" >Order

</code>

The Java Function which i am using below is,

<code>
<html:html locale="true">
<head>
<script src="usableforms.js"></script>
<script>
function init()
{
prepareForm();
}

function CheckUncheck(){

var size = document.forms[0].elements.length;
var checkFlag = document.forms[0].All.checked;
for (var i=0;i<size;i++) {
var box = document.forms[0].elements[i];
box.checked = checkFlag;
}
prepareForm();
}

function UncheckAll(){
var box = document.forms[0].All;
box.checked = 0;
}

</script>
</head>
</code>

But i am getting error as "document.forms.0.All.checked is null or not an object" ,when i check "All" Check button.

Also,i am getting error as "Undefined is null or not an object" when i check on "Default" Checkbox.

Also the Method which i have called on body load is also not working.

Can any one help me in this regard.

Thanks,
Srins.

rocknbil

9:10 pm on Dec 4, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Try this. Pass the form object and a check state to your routine.

if you're dynamically creating your checkboxes with perl or PHP, you can create any number of them this way (perl shown):


@selected_fields = ('some','list','of','selected','fields','static','or','user','input');

foreach $f (@fields) {
$chk_name = 'show_' . $f;
$checkboxes .= qq¦<input type="checkbox" name="$chk_name" id="$chk_name" value="$f"¦;
foreach $selected (@selected_fields) {
if ($f eq $selected) { $checkboxes .= ' checked'; last; }
}
$checkboxes .= " $f\n"; # label
}

So your final output would contain all your checkboxes plus the ever-important all on or all off checkboxes:

<input type="checkbox" name="chkson" id="chkson" onClick="checkBoxes(this.form,1);">All on
<input type="checkbox" name="chksoff" id="chksoff" onClick="checkBoxes(this.form,0);">All off
$checkboxes

Then your JavaSCRIPT: :-)


function checkBoxes(form,onoff) {
var sw = (onoff==1)?true:false;
for (i=0;i<form.elements.length;i++) {
var obj = form.elements[i];
if ((obj.type=='checkbox') && (obj.name!= 'chkson') && (obj.name!= 'chksoff')) {
obj.checked = sw;
}
}
if (onoff == 1) { form.chksoff.checked = false; }
else { form.chkson.checked = false; }
}