jQuery Required Field Validation

by Kyle Mitofsky

HTML

<form action="/contact/" method="POST" id="myForm">
    <input type="text" id="name" placeholder="Name" />
    <input type="email" id="email" placeholder="E-Mail"/>
    <textarea id="msg" rows="4" placeholder="Message"></textarea>
    <input type="submit" id="submit" value="Send"/>
</form>







<!-- Post Info -->
<div style='position:fixed;bottom:0;left:0;padding:5px; background:lightgray;width:100%;'>
    About this SO Post: <a href='http://stackoverflow.com/q/21384098/1366033'>Check if form is empty</a><br/>
    jQuery Docs: <a href='http://api.jquery.com/change/'>.change()</a><br/>
    jQuery Docs: <a href='https://api.jquery.com/toArray/'>.toArray()</a><br/>
    MDN: <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every'>Array.prototype.every()
</a><br/>
<div>

CSS

input, textarea { 
  display: block;
  box-sizing: border-box;
  margin-bottom: 5px;
  width: 200px;
  
}

JavaScript

// get all input elements and attach listener
var $inputs = $("#myForm :input:not([type='submit'])")
$inputs.change(function() {

  // check if all elements have value
  var allInputsHaveValue = $inputs.toArray().every(function(el) {
    return !!el.value
  });

  // toggle submit disabled
  $("#submit").prop("disabled", !allInputsHaveValue);

}).change(); // run on init