Theodore Steiner Theodore Steiner - 16 days ago 4x
CSS Question

Disable Button Until Fields are Full Pure JS

Trying to keep a button disabled until the form fields are filled in and I cannot seem to accomplish this. I've created a small example with a single field but the principle will be the same with a larger form.

Can anyone help?


function checkForm() {
var name = document.getElementById("name").value;
var cansubmit = true;

if (name.value.length == 0) {
cansubmit = false;

if (cansubmit == false) {
document.getElementById("submitbutton").disabled = true;


<input type="text" id="name" onkeyup="checkForm()" />

<button type="button" id="myButton">Test me</button>


There are a couple of mistakes in your sample:

  1. var name is assigned to the value string of the name element, then you check the value property of that - the string has no value property.
  2. the id of the submit button is myButton so use that id to get it by id (when setting the disabled attribute).
  3. You can disable the submitbutton until the length of the name input is greater than 0.

And disabling the button initially sounds like a good idea, right?

See corrected example below:

function checkForm()
    var name = document.getElementById("name").value;
    var cansubmit = (name.length > 0);
    document.getElementById("myButton").disabled = !cansubmit;

<input type="text" id="name" onkeyup="checkForm()" />

<button type="button" id="myButton" disabled="disabled">Test me</button>

You might also want to consider handling change via methods other than keypress - e.g. mouseup, etc... I tried adding onchange="checkForm()" and it works but only on blur (focus-change)...