我有一张注册表单,上面有两个复选框。如果未选中并且客户端单击注册按钮,则它将变为红色。
以下是我的复选框代码:-
$('#age_confirmation').change(function(){
var c = this.checked ? '' : 'red';
$('#age_confirmation').css('color', c);
});
$('#terms_of_service').change(function(){
var c = this.checked ? '' : 'red';
$('#terms_of_service').css('color', c);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" accept-charset="utf-8" class="form-signin form-register" role="form" id="register" autocomplete="off">
<div style="display:none"></div>
<input type="checkbox" id="age_confirmation" name="age_confirmation" required tabindex="10"/> Age Confirmation
<input type="checkbox" id="terms_of_service" name="terms_of_service" required tabindex="11"/> Terms of Service
<input type="submit" class="btn btn-tiffany" value="register" />
</form>
谁能告诉我哪里错了。任何帮助将不胜感激。
最佳答案
您需要使用 label
标签包裹输入的同级文本,并在输入更改时更改相关标签的颜色。设置复选框 input
的颜色不会影响旁边文本的颜色。
$('#age_confirmation').change(function(){
var c = this.checked ? '' : 'red';
$('#age_confirmation').next().css('color', c);
})
$('#terms_of_service').change(function(){
var c = this.checked ? '' : 'red';
$('#terms_of_service').next().css('color', c);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" accept-charset="utf-8" class="form-signin form-register" role="form" id="register" autocomplete="off">
<input type="checkbox" id="age_confirmation" name="age_confirmation" required tabindex="10"/>
<label for="age_confirmation">Age Confirmation</label>
<input type="checkbox" id="terms_of_service" name="terms_of_service" required tabindex="11"/>
<label for="terms_of_service">Terms of Service</label>
<input type="submit" class="btn btn-tiffany" value="register" />
</form>
你也可以简化你的代码
$('#register :checkbox').change(function(){
$(this).next().css('color', this.checked ? '' : 'red');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" accept-charset="utf-8" class="form-signin form-register" role="form" id="register" autocomplete="off">
<input type="checkbox" id="age_confirmation" name="age_confirmation" required tabindex="10"/>
<label for="age_confirmation">Age Confirmation</label>
<input type="checkbox" id="terms_of_service" name="terms_of_service" required tabindex="11"/>
<label for="terms_of_service">Terms of Service</label>
<input type="submit" class="btn btn-tiffany" value="register" />
</form>
关于javascript - 如果在表单提交期间未选中复选框,那么它将变为红色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53481855/