【发布时间】:2016-03-03 12:23:39
【问题描述】:
我需要验证文本、电子邮件、收音机、复选框、选择等输入字段。可以说我有这个:
<fieldset>
<div class="form-top">
<div class="form-bottom">
<div class="form-group">
<label class="sr-only" for="form-first-name">First name</label>
<input type="text" name="form-first-name" placeholder="First name..." class="form-first-name form-control" id="form-first-name">
</div>
<div class="form-group">
<label class="sr-only" for="form-last-name">Last name</label>
<input type="text" name="form-last-name" placeholder="Last name..." class="form-last-name form-control" id="form-last-name">
</div>
<div class="form-group">
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</div>
<div class="form-group">
<label class="sr-only" for="form-about-yourself">About yourself</label>
<textarea name="form-about-yourself" placeholder="About yourself..." class="form-about-yourself form-control" id="form-about-yourself"></textarea>
</div>
<button type="button" class="btn btn-next">Next</button>
</div>
</fieldset>
在 jQuery 中,我使用它来验证:
$('.registration-form .btn-next').on('click', function() {
var parent_fieldset = $(this).parents('fieldset');
console.log(parent_fieldset);
var next_step = true;
parent_fieldset.find('input[type="text"], input[type="radio"], input[type="password"], textarea').each(function() {
if( $(this).val() == "" ) {
$(this).addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
}
});
输入类型=text 和 textarea 验证有效,但输入类型=radio 无效。有什么想法吗?
更新 1 我正在处理一个多步骤表单,我使用这个example,在这个例子中我在第一步中添加了
<div class="form-group">
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</div>
【问题讨论】:
-
每个单选按钮都有值,所以
$(this).val()不为空...您必须检查所选单选按钮的值
标签: javascript jquery html