Search code examples
javascriptjqueryvalidationcheckboxtextbox

Validate a Textbox through a Javascript CheckBox


I am trying to validate a TextBox through a CheckBox ... The idea is the following, when the user unchecks the CheckBox (false) the field is not mandatory, but when he has the CheckBox marked (true) he has to enter the text, if he does not, I must send him a message on the screen ... I'm not sure how to do this ... any help for me?

Screenshot

View:

<script type="text/javascript">
        $(function (){
            $("#idcheckproveedor").change(function(){
                var st = this.checked;
                if (st) {
                    $("#txtSearch").prop("disabled", false);
                }
                else {
                    $("#txtSearch").prop("disabled", true);
                }
                });
            });

    </script>

     <div class="form-group">
                        <label>Proveedor</label>
                        <input type="checkbox" name="checkproveedor" id="idcheckproveedor" checked="checked" value="true"/>
                        @Html.TextBox("searchTerm", null, new { @class = "form-control", id = "txtSearch" })
                   </div>

Solution

  • Try the following way:

    $(function (){
      var st = $("#idcheckproveedor").attr('checked');
      $("#idcheckproveedor").change(function(){
        st = this.checked;
        if (st) {
            $("#txtSearch").prop("disabled", false);
        }
        else {
            $("#txtSearch").prop("disabled", true);
        }
        });
        $("#mybtn").click(function(){
          if(st && ($("#txtSearch").val() == "" || $("#txtSearch").val() == null)){
            alert("Please enter text");
            return false;
          }
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    
    <div class="form-group">
      <label>Proveedor</label>
      <input type="checkbox" name="checkproveedor" id="idcheckproveedor" checked="checked" value="true"/>
      <input type="text" id="txtSearch"/>
    </div>
    <button id="mybtn">Click</button>