26

ユーザーがテキストを提供していない場合、送信ボタンを無効にしようとしています。

一見すると、すべて問題なく動作しているように見えますが、ユーザーがテキストを入力して削除すると、送信ボタンが有効になります。

これが私のコードです:

$(document).ready(function(){
    $('.sendButton').attr('disabled',true);
    $('#message').keyup(function(){
        if($(this).val.length !=0){
            $('.sendButton').attr('disabled', false);
        }
    })
});
4

5 に答える 5

3

これを試してください

<!DOCTYPE html>
<html>
  <head>
    <title>Jquery</title>
    <meta charset="utf-8">       
    <script src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
  </head>

  <body>

    <input type="text" id="message" value="" />
    <input type="button" id="sendButton" value="Send">

    <script>
    $(document).ready(function(){  

      var checkField;

      //checking the length of the value of message and assigning to a variable(checkField) on load
      checkField = $("input#message").val().length;  

      var enableDisableButton = function(){         
        if(checkField > 0){
          $('#sendButton').removeAttr("disabled");
        } 
        else {
          $('#sendButton').attr("disabled","disabled");
        }
      }        

      //calling enableDisableButton() function on load
      enableDisableButton();            

      $('input#message').keyup(function(){ 
        //checking the length of the value of message and assigning to the variable(checkField) on keyup
        checkField = $("input#message").val().length;
        //calling enableDisableButton() function on keyup
        enableDisableButton();
      });
    });
    </script>
  </body>
</html>
于 2013-07-17T12:43:10.647 に答える
1

coffeescriptを使用する人のために、最も広く使用されているフォームの送信ボタンを無効にするためにグローバルに使用するコードを追加しました。上記のアディルの回答の適応。

$('#new_post button').prop 'disabled', true
$('#new_post #post_message').keyup ->
    $('#new_post button').prop 'disabled', if @value == '' then true else false
    return
于 2016-11-28T15:08:14.937 に答える