JQuery canonical approach for dynamically enabling / disabling form submission buttons

I am writing JavaScript to handle a general scenario for dynamically enabling a form submit button when any text is entered in the corresponding text field. I have been using the Prototype framework for many years, but am moving on to jQuery. So I was surprised to find that the jQuery version of my code looks rather awkward.

Is there a way to avoid referencing elements of a null array 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>
+3
source share
1 answer

jQuery attr . [0] jQuery, DOM disabled - jQuery.

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

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

Source: https://habr.com/ru/post/1762322/


All Articles