JQuery的条件与空白输入
问题描述:
我需要做多项检查的jQuery的条件......JQuery的条件与空白输入
我期待这样的事情:
IF checkbox_A被选中,那么
如果input_A是空的然后alert('input_A is Required')
else else class =“continue”to the div below。
<button id="btn1">Continue</button>
可能吗?
答
我通常不会这样做,因为你甚至没有显示自己写任何代码的尝试,但我心情很好。
if ($("#checkboxA").is(":checked")) {
if ($("#inputA").val() == "") {
alert("input_A is required");
}
else {
$("#btn1").addClass("continue");
}
}
答
$(document).ready(function() {
if($("#yourCheckBoxId").is(":checked")) {
if($("#yourInputId").val() == "") {
alert("empty");
}
else {
$("button[id='btn1']").addClass("continue");
}
}
});
答
也许
if (document.getElementById('checkbox_A').checked){
if (document.getElementById('input_A').value == ''){
alert('input_A is Required')
} else {
$('#btn1').addClass('continue;);
}
}
但如果你要验证你能避免各场的人工检查,并通过添加required
类元素自动多元素是必需的。
<input type="text" name="...." class="required" />
现在,当你想验证表单你做
// find the required elements that are empty
var fail = $('.required').filter(function(){return this.value == ''});
// if any exist
if (fail.length){
// get their names
var fieldnames = fail.map(function(){return this.name;}).get().join('\n');
// inform the user
alert('The fields \n\n' + fieldnames + '\n\n are required');
// focus on the first empty one so the user can fill it..
fail.first().focus();
}
答
是的,这是可能的:
$('#checkBoxA').click(function() {
var checkBoxA = $('#checkBoxA');
var textBoxA = $('#textBoxA');
if (checkBoxA.checked())
{
if (textBoxA.val() == "")
{
$('#btn1').removeClass('continue');
alert("No value entered");
textBoxA.focus();
}
else {
$('#btn1').addClass('continue');
}
} else {
$('#btn1').addClass('continue');
}
});