next Posted August 21, 2008 Share Posted August 21, 2008 I'm trying to check and uncheck all checkboxes in myForm, but keep getting errors. JS: <script language="javascript"> function handleChboxes(type) { switch(type) { case 'select': for(var i = 0; i <= document.myForm.elements.length; i++) { if(document.myForm.elements[i].type == 'checkbox' && document.myForm.elements[i].checked = false) document.myForm.elements[i].checked = true; } break; case 'deselect': for(var i = 0; i <= document.myForm.elements.length; i++) { if(document.myForm.elements[i].type == 'checkbox' && document.myForm.elements[i].checked = true) document.myForm.elements[i].checked = false; } break; } } </script> form: echo '<form name="myForm" action="' . $_SERVER['PHP_SELF'] . '" method="post"><ul id="menu"> <li><a href="#" onClick="action(\'deselect\')">deselect all</a></li> <li><a href="#" onClick="action(\'select\')">select all</a></li> </ul></form>'; error #1: invalid assignment left-hand side [break on this error] if(document.myForm.elements.ty...ent.myForm.elements.checked = false)\n error #2: happens after i click "select all" action is not defined [break on this error] action("select"); same stuff happens when i click "deselect all". How would i go about fixing those? Thanks. Quote Link to comment Share on other sites More sharing options...
akitchin Posted August 21, 2008 Share Posted August 21, 2008 1. it's because you're using the assignment operator, rather than the comparison operator (= vs. ==). you don't need the second condition in the if() statement though - simply set the checked property to true or false respectively. 2. you're calling your function handleCheckboxes(), not action(). Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 23, 2008 Share Posted August 23, 2008 That a LOT of unnecessary code. Make life easier on yourself. 1. Give functions logical names. 'action' or 'handleChboxes' don't give enough information as to what is being done. 2. Pass appropriate values (i.e. don't pass an arbitrary value such as 'select' that you then need to translate into the value you really need - true) 3. Don't repeat/copy code unnecessarily. The main part of the code above is duplicated with only 1 line being different. This function would do all that the above would do and would be much more efficient function checkAll(checkBool) { for(var i = 0; i <= document.myForm.elements.length; i++) { if(document.myForm.elements[i].type == 'checkbox') { document.myForm.elements[i].checked = checkBool; } } } (I would also pass the form name to that function to make it more modular) And you would call it like this: <li><a href="#" onClick="checkAll(false)">deselect all</a></li> <li><a href="#" onClick="checkAll(true)">select all</a></li> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.