8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

空欄だったら、ボタンを使用不能にするセット

Last updated at Posted at 2014-03-25

こんなフォームがあったとして、

test.html
<form id="hoge" action="login.php" method="post" >
  <label class="input_label" for="user_login">ユーザー名:</label>
  <input name="log" value="" class="input" id="user_login" type="text"><br />
  <label class="input_label" for="user_pass">パスワード:</label>
  <input name="pwd" class="input" id="user_pass" type="password"><br />
  <input class="button" name="submit" id="submit" value="ログイン" type="submit">
</form>

こんな感じで書くと、

test.html
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script type="text/javascript">
$(function(){
    $("#submit").prop('disabled', true);
    $("#submit").css('color', '#AAA');
    $("input[name='log']").blur(function(){
        $("#submit").css('color', '#000');
        if($("input[name='log']").val() == "" || $("input[name='pwd']").val() == "" ){
            $("#submit").prop('disabled', true);
            $("#submit").css('color', '#AAA');
        } else {
            $("#submit").prop('disabled', false);
        }
    });
    $("input[name='pwd']").blur(function(){
        $("#submit").css('color', '#000');
        if($("input[name='log']").val() == "" || $("input[name='pwd']").val() == "" ){
            $("#submit").prop('disabled', true);
            $("#submit").css('color', '#AAA');
        } else {
            $("#submit").prop('disabled', false);
        }
    });
});
</script>

フォームが空欄だったら、ボタンを使用不能にすることができる

思うところあって書き直してみたのが下。

test.html
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script type="text/javascript">
$(function(){
    disabled_btn();
    $("input[name='log']").blur(function(){
        change_btn();
    });
    $("input[name='pwd']").blur(function(){
        change_btn();
    });

    function disabled_btn() {
        $("#submit").prop('disabled', true);
        $("#submit").css('color', '#AAA');
    }

    function change_btn() {
        $("#submit").css('color', '#000');
        if($("input[name='log']").val() == "" || $("input[name='pwd']").val() == "" ){
            disabled_btn();
        } else {
            $("#submit").prop('disabled', false);
        }
    }
});
</script>
8
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?