Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 693
John Topley Avatar asked Nov 24 '25 16:11

John Topley


1 Answers

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);
});
like image 86
Anurag Avatar answered Nov 27 '25 06:11

Anurag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!