John Topley
John Topley

Reputation: 115372

Canonical jQuery approach to dynamically enabling/disabling form submit buttons

I'm writing some JavaScript to handle the common scenario of dynamically enabling a form submit button when some text is entered in an associated text field. I've been using the Prototype framework for years but am moving over to jQuery. So I was surprised to discover that the jQuery version of my code seems kind of clunky.

Is there a way to avoid having to reference the zeroth array elements in my jQuery code below, or a more canonical jQuery approach in general?

<form action="...">
  <input id="subject" type="text" />
  <input id="save" type="submit" value="Save" disabled="disabled" />
</form>
<script type="text/javascript">

  // Prototype version
  $("subject").observe("keyup", function() {
    $("save").disabled = $("subject").value.length == 0;
  });

  // jQuery version
  $("#subject").keyup(function() {
    $("#save")[0].disabled = $("#name")[0].value.length == 0;
  });
</script>

Upvotes: 3

Views: 308

Answers (1)

Anurag
Anurag

Reputation: 141879

In jQuery, use the attr method to set an attribute on the element. By getting the first item [0] in the jQuery set, you are directly manipulating the native DOM element's disabled property - that is not jQuery.

$("#save").attr('disabled', true);

$("#subject").keyup(function() {
    $("#save").attr('disabled', $("#name").val().length == 0);
});

Upvotes: 4

Related Questions