jQuery disable/enable submit button

Posted in :

避免使用者重覆按某一個按鈕.

解法1:

$(document).ready(function() {
     $(':input[type="submit"]').prop('disabled', true);
     $('input[type="text"]').keyup(function() {
        if($(this).val() != '') {
           $(':input[type="submit"]').prop('disabled', false);
        }
     });
 });

解法2:

$(function() {
  $(":text").keypress(check_submit).each(function() {
    check_submit();
  });
});

function check_submit() {
  if ($(this).val().length == 0) {
    $(":submit").attr("disabled", true);
  } else {
    $(":submit").removeAttr("disabled");
  }
}

HTML

The “disabled” in <input type="button" disabled> in the markup is called a boolean attribute by the W3C.

HTML vs. DOM

Quote:

A property is in the DOM; an attribute is in the HTML that is parsed into the DOM.

https://stackoverflow.com/a/7572855/664132

jQuery

Related:

Nevertheless, the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does. Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property.

Relevant:

Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method.

$( "input" ).prop( "disabled", false );

Summary

To […] change DOM properties such as the […] disabled state of form elements, use the .prop() method.

(http://api.jquery.com/attr/)

As for the disable on change part of the question: There is an event called “input”, but browser support is limited and it’s not a jQuery event, so jQuery won’t make it work. The change event works reliably, but is fired when the element loses focus. So one might combine the two (some people also listen for keyup and paste).

Here’s an untested piece of code to show what I mean:

$(document).ready(function() {
    var $submit = $('input[type="submit"]');
    $submit.prop('disabled', true);
    $('input[type="text"]').on('input change', function() { //'input change keyup paste'
        $submit.prop('disabled', !$(this).val().length);
    });
});

資料來源:
https://stackoverflow.com/questions/1594952/jquery-disable-enable-submit-button

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *