doe doe - 4 months ago 14
HTML Question

button disabled while required fields are empty

I'm using this template for forms. For text inputs, it provides the opportunity to validate the input (simple: if it's empty, red box, if it's not, green box). However, I want my submit button (markup below) to be clickable only if all necessary fields are at least not empty.

<button type="submit" name="finish" class="waves-effect waves-light btn">


Regards

Answer

Use oninput to immediately reflect changes in inputs and check if any input is empty.

HTML

    <form id="frm">
      <input type="text" name="input1" oninput="testFinish();" />
      <input type="text" name="input2" oninput="testFinish();" />
      <button type="submit" name="finish" disabled onsubmit="alert('SUBMITTED')">Finish</button>
    </form>

JAVASCRIPT

function testFinish(){
var frm = document.getElementById('frm');
if (frm['input1'].value && frm['input2'].value)
  frm['finish'].disabled = false;
}

JsFiddle

Comments