Because of the special nature of the Checkbox, we usually define a function to select all or invert the Checkbox instance. the Checkbox Processing Method in jquery and js will be different. Let's take a look at it.
Use JS to select all checkpoints in the FORM.
Javascript code:
The Code is as follows: |
Copy code |
<SCRIPT language = javaScript>
// Select all or not all Function checkall (){ Var isChecked = (document. form1.checkAll. checked = true ); Var elements_all = document. form1.elements; For (I = 0; I <elements_all.length; I ++ ){ Var element = elements_all [I]; If (element. type = "checkbox "){ Element. checked = isChecked; } } }
// Check whether any checkbox is selected Function anyChecked (){ Var elements_any = document. form1.elements; For (I = 0; I <elements_any.length; I ++ ){ Var element = elements_any [I]; If (element. checked = true ){ Return true; } } Return false; }
</SCRIPT> HTML code: <FORM onsubmit = "return anyChecked ()" method = post name = form1 action = ""> Select All: <INPUT id = checkAll onclick = checkall () type = checkbox> Multiple choice box list: <INPUT value = 1 type = checkbox name = cb> <INPUT value = 2 type = checkbox name = cb> <INPUT value = 3 type = checkbox name = cb> <INPUT value = submit type = submit name = Submit> </FORM> |
Let's look at another jquery instance.
JQuery. attr gets/Sets object attribute values, such:
$ ("Input [name = 'chk _ list']"). attr ("checked"); // read the status of all objects whose names are 'chk _ List' (whether or not selected)
$ ("Input [name = 'chk _ list']"). attr ("checked", true); // set the checked value of all objects whose names are 'chk _ list' to true.
The Code is as follows: |
Copy code |
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <Html xmlns = "http://www.w3.org/1999/xhtml"> <Head runat = "server"> <Title> jQuery Selects all and does not select all checkpoints </title> <Script src = "http://code.jquery.com/jquery-1.4.4.min.js" type = "text/javascript"> </script> <script type = "text/javascript"> $ (Function (){ $ ("# CheckAll"). click (function (){ $ ('Input [name = "subBox"] '). attr ("checked", this. checked ); }); Var $ subBox = $ ("input [name = 'subbox']"); $ SubBox. click (function (){ $ ("# CheckAll"). attr ("checked", $ subBox. length ==$ ("input [name = 'subbox']: checked"). length? True: false ); }); }); </Script> </Head> <Body> <Div> <Input id = "checkAll" type = "checkbox"/> select all <Input name = "subBox" type = "checkbox"/> Item 1 <Input name = "subBox" type = "checkbox"/> Item 2 <Input name = "subBox" type = "checkbox"/> Item 3 <Input name = "subBox" type = "checkbox"/> Item 4 </Div> </Body> </Html> |