Below is a very nice piece of code with toggles to select all or none of a set of selection boxes (source). The code works very well for me for what I plan to do with it, since with this javascript it is very easy to select only a manual subset instead of all of the checkboxes in the form by changing the 'for' values in the script. However, I need to have one button that does both selecting and deselecting of checkboxes instead of two separate buttons as below. There are other examples of code online that can do this but this code is better understandable to me and more flexable for the purpose I have in mind than other code examples that I found and I am not able to combine them. I have no experience to javascript. It frustrates me that I can't get a satifying solution while it is probably not that difficult ones you have more experience... Hope someone can tell my how to change the code below to one button that changes function from 'select all' to 'select none' once the user has clicked on it, or does something that has the same effect.
<form name="theForm">
My favorite programming/scripting language is:<p>
Select <a href="javascript:selectToggle(true, 'theForm');">All</a> | <a href="javascript:selectToggle(false, 'theForm');">None</a><p>
<input type="checkbox" name="answers[]" value="javascript">JavaScript<p>
<input type="checkbox" name="answers[]" value="perl">Perl<p>
<input type="checkbox" name="answers[]" value="php">PHP<p>
<input type="checkbox" name="answers[]" value="c++">C++
</form>
<script>
function selectToggle(toggle, form) {
var myForm = document.forms[form];
for( var i=0; i < myForm.length; i++ ) {
if(toggle) {
myForm.elements[i].checked = "checked";
}
else {
myForm.elements[i].checked = "";
}
}
}
</script>
Help is very much appreciated.
` without the closing `
`. None of your `` are closed correctly either but that minor compared to the `` tags. It might cause problems later with styles and JS (DOM).
– Biotox May 07 '13 at 16:14