Search code examples
hyperscript

Select all checkboxes using hyperscript


I'm trying to select all checkbox from a click event on a button, but I cannot found a way to do it propertly, here is the best code that I can think of:

<p><strong><span _="on change from <input[name='test']/> or load
                    put (<input[name='test']:checked/>).length into me"></span></strong> selected</p>

<button _="on click add @checked to <input[name='test']/>">Select All</button>
<input type="checkbox" name="test" />
<input type="checkbox" name="test" />
<input type="checkbox" name="test" />
<input type="checkbox" name="test" />

<script src="https://unpkg.com/[email protected]"></script>

But unfortunately its not working, it adds a checked="undefined" on all checkboxes, all get checked, but when I uncheck some it stops working. Seems like I shouldn't use the checked attribute, maybe use the checked property thought javascript.

The solution must use the Hyperscript library ( https://hyperscript.org )


Solution

  • Found a way to do it, more verbose than I wanted to, but it works. I had to use the click() method to trigger the change event, only setting the checked property to true was not enough, because my checked counter need to listen to the changed event.

    <button _="on click  
               set value to ((<input[name='test']:not(:checked)/>).length == 0)
               repeat in <input[name='test']/>
                 set it.checked to value
                 it.click() 
               end">Select All</button>
    <input type="checkbox" name="test" />
    <input type="checkbox" name="test" />
    <input type="checkbox" name="test" />
    <input type="checkbox" name="test" />
    
    <p><strong><span _="on change from <input[name='test']/> or load
                        put (<input[name='test']:checked/>).length into me"></span></strong> selected</p>
    
    <script src="https://unpkg.com/[email protected]"></script>