rayphi rayphi - 2 years ago 141
Javascript Question

Toggle for multiple checkboxes – prototype js

I'm trying to implement a toggle for multiple checkboxes but if I switch one manually, the checkbox is no longer considered by toggle.

var publishAll = $("toggle");
publishAll.observe('click', function(e){
var state = null;
if(this.checked) {
state = "checked";
$$('.checkbox').invoke('writeAttribute', 'checked', state);

<script src="https://ajax.googleapis.com/ajax/libs/prototype/"></script>
<input id="toggle" type="checkbox" name="toggle" value="true"> Toggle checkbox<br /><br />

check these manually and it won't work with toggle anymore.<br />
<input class="checkbox" type="checkbox" name="checkbox[]" value="1"><br />
<input class="checkbox" type="checkbox" name="checkbox[]" value="2">

Have I done something wrong?

Answer Source

Instead of trying to set the attribute of checked to "checked" you need to use the javascript true or false as well as use the setValue() method

So you can simplify your javascript like this

$("toggle").observe('click', function(e){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download