gpt4 book ai didi

javascript - 根据输入类型 = radio/checkbox/select 使用 jQuery 进行验证

转载 作者:行者123 更新时间:2023-12-03 07:32:14 25 4
gpt4 key购买 nike

我需要验证输入字段,例如文本、电子邮件、广播、复选框、选择。可以说我有这个:

<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');
}
});

输入类型=文本和文本区域验证有效,但输入类型= 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() 中您应该检查的 radio :

($this).find(":selected").text();

编辑

一个小例子:

$('.btn').on('click', function() {
$("input[type='radio']").each(function() {
var radioName= $(this).attr('name');
var isChecked =$("input[name='"+radioName+"']:checked").val();

if( $(this).val() != "" && isChecked){
$("#result").html('success');
}
else {
$("#result").html('error');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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 id="result"></div>
<input type="button" class="btn" value="send"/>

关于javascript - 根据输入类型 = radio/checkbox/select 使用 jQuery 进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35772123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com