tags:

views:

76

answers:

4
<script language="javascript" type="text/javascript">
var a =10;
function test()
{
 if ( a ==10) {
   document.sample.checkbox1.checked = true ; 
  }

}

</script>

<form name="sample">

 <input type="checkbox" name="checkBox1" test();>Option

</form>

While creating form itself its automatically call function based on it should decide whether its need to checked or not ..

Here the question . How to call the function without any click ( on click event )

Thanks , Chells

A: 

It sounds to me like you want to call it in the onLoad event of the body tag. But perhaps you could explain more about why you want to call this function in the first place?

ysth
i just want to enable the checkbox basesd on the variable . i will move around the page then if the comee back to check box . it should be automatically call function based on the variable it should decide .. whether i need to checked or not . ?
joe
+2  A: 

You could run the test() function in the body's onLoad handler:

<body onLoad="test();">

This will call the function once the page's content has been loaded.

You could also just call the function in <script> tags after the inputs:

<form name="sample">
    <input type="checkbox" name="checkBox1">Option    
</form>

<script language="JavaScript" type="text/javascript">
    test();
</script>

This will be called as the page is loaded.

Perspx
`<body onload="...">` sets `window.onload`, ie it *WILL* wait for external resources to load! If you don't want to wait for that, you need a DOMContentLoaded listener (or use an apropriate hack in browsers which don't support the event natively)
Christoph
Ah, yes, thanks!
Perspx
No point in using the "language" attribute as all JavaScript-supporting browsers default to JavaScript... You'll want to use a type attribute if you want it to validate though.
J-P
J-P
A: 

As Perspx said, throw it in an event for the body's onload, but look into an event lib (like mine) because there is better support and flexibility for them than inline events.

Christian
+1  A: 

There's always good old document.writeln(), even if it's been succeeded by DOM manipulation in most use cases:

<script type="text/javascript">
document.writeln('<input type="checkbox" name="checkBox1"' +
    (a == 10 ? ' checked' : '') + '>');
</script>
<noscript>
 <!-- unchecked by default -->
 <input type="checkbox" name="checkBox1">
</noscript>
Christoph