我正在尝试通过CheckBox验证TextBox ...想法如下,当用户取消选中CheckBox(false)时,该字段不是必需的,但是当他将CheckBox标记为(true)时,他必须输入文字,如果他没有,我必须在屏幕上给他发消息......我不知道该怎么做...对我有什么帮助?
查看:
<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>
答案 0 :(得分:0)
尝试以下方式:
$(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;
}
});
});
&#13;
<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>
&#13;
答案 1 :(得分:0)
$( 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>
希望这会对你有所帮助。