Enable submit button when all input fields are valid in Hyperscript?

1.6k Views Asked by At

I'm playing around with htmx and hyperscript and I want the "submit button" (Add User) to be enabled when all required input fields are valid in a form. In this case, a non-empty name and a valid email address must have been defined.

<form hx-post="/example" hx-target="#table tbody" hx-swap="beforeend">
        <label class="control-label" for="nameInput">Name</label>
        <input id="nameInput" name="name" class="form-control" type="text" required placeholder="John Doe"/>
        
        <label class="control-label" for="emailInput">Email</label>
        <input id="emailInput" name="email" class="form-control" type="email" required placeholder="[email protected]"/>
        <button _="<what should I write here??>" class="btn btn-primary" disabled>Add User</button>
    </div>
</form>

What should I write instead of <what should I write here??> to make this happen?

2

There are 2 best solutions below

0
On BEST ANSWER

Something like this should work:

<button _="on change from closest <form/>
             for elt in <[required]/>
               if the elt's value is empty
                 add @disabled then exit
               end
             end
             remove @disabled" class="btn btn-primary" disabled>Add User</button>

https://jsfiddle.net/xy8vn5jk/20/

0
On

I like @1cg answer

I have slightly more stringent requirements than the OP.

What I required is such that when the user types but doesn't leave the focus, the button should still disable or enable correctly.

If use keyup is wiser to use debounced,

hence my version is

<button _="on keyup from closest <form/> debounced at 150ms
            if (<[required]:invalid/>).length > 0
                add @disabled
                put 'Check All Fields' into me
                then exit
            end
            remove @disabled
            put 'Submit' into me
            " disabled type="submit">
              Fill Out Required Fields
</button>

https://codepen.io/simkimsia/pen/LYQgZZK

by using [required]:invalid and comparing the length you can avoid doing a for loop and a nested if. Please note the parenthesis to wrap ([required]:invalid)