简体   繁体   English

通过JavaScript复选框验证文本框

[英]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? 我正在尝试通过CheckBox验证TextBox ...的想法如下,当用户取消选中CheckBox(false)时,该字段不是必填字段,但是当他将CheckBox标记为(true)时,他必须输入文本,如果他没有,我必须在屏幕上向他发送一条消息...我不确定该怎么做...对我有没有帮助?

屏幕截图

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>

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> 

 $( document ).ready(function() { $('body').on('click','.btn-submit',function(){ var checked = $('#checked_indicator').is(':checked'); var validate = true; var field = $('#field_only').val(); if(checked){ if(field == ''){ validate =false; } } if(validate){ //code here for field is not required alert('Your field: '+field); }else{ //code here for field is required alert('Field is Required'); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="form_test"> <input type="checkbox" id="checked_indicator" /> <input type="field" id="field_only" /> <button type="button" class="btn-submit" >Submit</button> </form> 

Hope this will help you. 希望这会帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM