jQuery : disable submit button if field empty or checkbox not checked

时间:2018-08-22 13:59:49

标签: javascript jquery

It's the first time I'm using jQuery and I need your help because I don't overcome to make what I want.

I have a table of documents with a checkbox for each document in order to select it or not.

I have also a field in which one users set a new year in order to modify filename after.

I have this process :

  1. By default, submit button is disabled
  2. To activate the submit button, user have to check one checkbox AND write the new year
  3. Once the step 2 is done, if I remove year OR uncheck the checkbox, submit button have to be disabled

This is my javascript part (don't forget, it's my first time) :

<script type="application/javascript">

$(document).ready(function(){
    $('#DocumentButton').attr('disabled',true);
    $('#year').keyup(function(){
        // if field year is not empty and checkbox is checked
        if($(this).val().length !=0 && $('.fakeRadio').is(':checked'))
            $('#DocumentButton').attr('disabled', false);
        // if field year is empty or checkbox isn't checked
        else if ($(this).val().length =0 || $('.fakeRadio').is(':checked')==false)
            $('#DocumentButton').attr('disabled',true);
    })
});

   // Simulate Checkbox as Radiobox
   $(document).ready(function(){
      $(".fakeRadio").click(function(){
      var wasChecked = !$(this).prop("checked");
      $(".fakeRadio").prop( "checked", false );
      $(this).prop("checked", (!wasChecked) ? true : false );
      });
    });

  </script>

And the according HTML part :

<div class="col-md-offset-1 col-md-5">
  <h4> {% trans "List of documents:" %} </h4>
  <form action="" method="POST"> {% csrf_token %}
    <table id="DocumentTable" class="table table-bordered table-striped table-condensed table_model"
           style="width: 160%;">
      <thead>
      <tr>
        <th style="width: 10%;">Choice</th>
        <th>Document title</th>
      </tr>
      </thead>
      <tbody>
      {% for document in query_document %}
        <tr>
          <td><input type="checkbox" class="fakeRadio" id="DocumentCheckBox" name="DocumentChoice" value="{{ document.id }}"></td>
          <td>{{ document.title }}</td>
        </tr>
      {% endfor %}
      </tbody>
    </table>

    <input type="text" id="year" name="q1year" placeholder="Set new year" value="{{ request.get.q1year }}">
    <button class="btn btn-default" id="DocumentButton" type="submit" name="UpdateDocument">{% trans "Submit" %}</button>
  </form>
</div>

Up to now, the process works fine with step 1 and 2, but not if I uncheck the checkbox.

Could you help me and explain what is false in my code ?

5 个答案:

答案 0 :(得分:1)

尝试一下:

class Foo
{

    public function methodOne()
    {
        $this->methodTwo();
        echo "<p>methodOne continuing execution</p>";
        debug_print_backtrace();
        echo "<hr>";
    }

    public function methodTwo()
    {
        try {
            $this->methodThree();
        } catch (Exception $e) {
            echo "<p>methodTwo caught error</p>";
            debug_print_backtrace();
            echo "<hr>";
        }

        echo "<p>methodTwo continuing execution</p>";
        debug_print_backtrace();
        echo "<hr>";
    }

    public function methodThree()
    {
        debug_print_backtrace();
        echo "<hr>";
        throw new Exception('exception happened');
    }
}

check it online


您可以更短地编写$(function(){ function Op(){ if($("table :checked")[0] && $("#year").val()) $("#DocumentButton").removeAttr("disabled"); else $("#DocumentButton").attr("disabled", ""); }; $("table").on("change", ":checkbox", Op); $("#year").on("input", Op); Op(); }); 函数:

op

Try this live!

提示:您可以在$(function(){ function Op(){ $("#DocumentButton").prop("disabled", !($("table :checked")[0] && $("#year").val())); }; $("table").on("change", ":checkbox", Op); $("#year").on("input", Op); Op(); }); 中进行所有操作(是否通过验证)。我一直在我的项目中使用这种方式,并且一切都很好并且可管理。也可以在所有浏览器版本中使用。

答案 1 :(得分:1)

HTML5验证可以为您完成此任务。无需JavaScript。只需将required属性添加到元素。

<form>
  <label>

  <label for="name">name</label><input id="name" required />
  <br/>
  <input type="checkbox" required name="terms"> I accept the Terms and Conditions
  </label>
  <br/>

  <input type="submit">
</form>

但是,如果您想使用JavaScript进行操作,则可以采用一种方法进行两项检查。仅用一种方法进行所有检查比尝试弄清楚如何对每个输入进行单独检查要容易得多。

function checkValid () {
  var cbChecked = $("#cb").is(":checked");  // check if checked
  var hasText = $("#name").val().length > 0;  // check if it has text
  
  $("#btnSubmit").prop("disabled", !cbChecked || !hasText);
}

$( function () {
  checkValid(); // run it for the first time
  $("#cb").on("change", checkValid);  // bind checkbox
  $("#name").on("input", checkValid)  // bind textbox
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <label>

  <label for="name">name</label><input id="name" />
  <br/>
  <input id="cb" type="checkbox" name="terms"> I accept the Terms and Conditions
  </label>
  <br/>

  <input type="submit" id="btnSubmit">
</form>

如果您在e复选框上有多个复选框,并且只需要一个复选框,则说明您不需要使用JavaScript

function checkValid () {
  var cbChecked = $(".cb:checked").length > 0;  // check if at least one checked
  var hasText = $("#name").val().length > 0;  // check if it has text
  
  $("#btnSubmit").prop("disabled", !cbChecked || !hasText);
}

$( function () {
  checkValid(); // run it for the first time
  $(".cb").on("change", checkValid);  // bind checkboxesvia classname
  $("#name").on("input", checkValid)  // bind textbox
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <label>

  <label for="name">name</label><input id="name" />
  <br/>
  <label>
  <input class="cb" type="checkbox" name="terms"> One
  </label>
  <label>
  <input class="cb" type="checkbox" name="terms"> Two
  </label>
  <label>
  <input class="cb" type="checkbox" name="terms"> Three
  </label>
  <br/>

  <input type="submit" id="btnSubmit">
</form>

答案 2 :(得分:0)

  

在页面的初始加载中,提交按钮将被禁用,如果用户单击复选框(或)在输入字段中输入一些值,则禁用按钮将被删除

   $(document).ready(function(){
      inputType();
      checkbox();
      $('#DocumentButton').attr('disabled',true); //Initial load of the page submit button will be disabled
    });

function inputType(){
        if($("#year").val() == ''){
           $('#DocumentButton').attr('disabled',true);
        }else{
           $('#DocumentButton').attr('disabled',false);
        }         
 }

function checkbox(){
    $('.fakeRadio').each(function () {
        if ($(this).prop('checked')==true){ 
           $('#DocumentButton').attr('disabled', false);
        }else{
           $('#DocumentButton').attr('disabled', true);
        }
    });
}
  

而不是为输入字段和复选框编写一个onclick和onkeyup函数

  <td><input type="checkbox" onclick="checkbox()" class="fakeRadio" id="DocumentCheckBox" name="DocumentChoice" value="{{ document.id }}"></td>

 <input type="text" onkeyup="inputType()" id="year" name="q1year" placeholder="Set new year" value="{{ request.get.q1year }}">

答案 3 :(得分:0)

您非常接近,请尝试以下操作:

$(document).ready(function(){
    $('#year').keyup(function(){
        if($(this).val().length > 0)
            if($('.fakeRadio:checked').length() > 0){
                 $('#DocumentButton').attr('disabled', false);
            }
        } else {
            $('#DocumentButton').attr('disabled', true);
        }
    });

    $('.fakeRadio').on('change', function(){
        var checked = $('.fakeRadio:checked').length();
        if(checked > 0 && $('#year').val().length > 0){
            $('#DocumentButton').attr('disabled', false);
        } else {
            $('#DocumentButton').attr('disabled', true);
        }
    });
});

答案 4 :(得分:0)

问题是您仅在input keyup事件中检查有效性并禁用或禁用按钮,而不在click的{​​{1}}事件中禁用或禁用按钮。

您应该将有效性检查代码放在函数中,并在两个事件中都调用它-

checkbox

顺便说一句,不需要进行2个不同的$(document).ready(function(){ $('#DocumentButton').attr('disabled',true); $('#year').keyup(function(){ checkValidity(); }) }); // Simulate Checkbox as Radiobox $(document).ready(function(){ $(".fakeRadio").click(function(){ var wasChecked = !$(this).prop("checked"); $(".fakeRadio").prop( "checked", false ); $(this).prop("checked", (!wasChecked) ? true : false ); checkValidity(); }); }); function checkValidity() { // if field year is not empty and checkbox is checked if($('#year').val().length !=0 && $('.fakeRadio').is(':checked')) $('#DocumentButton').attr('disabled', false); // if field year is empty or checkbox isn't checked else if ($('#year').val().length =0 || $('.fakeRadio').is(':checked')==false) $('#DocumentButton').attr('disabled',true); } 通话。您可以将所有代码放在同一代码中。