[英]Form Validation - Radio Loop
I am trying to validate a section of my form using JS. 我试图使用JS验证我的表单的一部分。 The user should click one of 3 radio buttons.
用户应单击3个单选按钮中的一个。 If none of them are selected, the value of a certain variable ($planSelectValid) should be false.
如果未选择任何一个,则某个变量($ planSelectValid)的值应为false。 If the user clicks one of the radios, it should switch the value to true.
如果用户单击其中一个无线电,则应将该值切换为true。 From this, I can later check the variable to ascertain whether the submit button should be active.
由此,我可以稍后检查变量以确定提交按钮是否应该是活动的。
I have spent a good amount of time on this and I cannot seem to get this to work correctly. 我花了很多时间在这上面,我似乎无法让它正常工作。 I have to admit that I am still rather green when it comes to JS.
我不得不承认,在JS方面,我还是比较绿色。 What am I missing/doing-wrong?
我错过了什么/做错了什么? Any help with this is most appreciated :)
对此有任何帮助,非常感谢:)
Here are the relevant parts of my code: 以下是我的代码的相关部分:
HTML
<div class="socPlanRadios">
<p>
<input type="radio" name="socPlan" value="Plan 1" id="plan1">
<label for="plan1"><b>Plan 1</b></label>
</p>
<p>
<input type="radio" name="socPlan" value="Plan 2" id="plan2">
<label for="plan2"><b>Plan 2</b></label>
</p>
<p>
<input type="radio" name="socPlan" value="Plan 3" id="plan3">
<label for="plan2"><b>Plan 3</b></label>
</p>
</div>
JS
<script>
$planSelectValid = false;
function ValidateRadioButtons() { //Function for Validating If Radio Button isselected
$('.socPlanRadios').find('radio').each(function () { //LoopingthroughradioButtons
if ($(this).is(':checked')) {
$planSelectValid = true;
}
});
if ($planSelectValid = true) {
alert("Validation Passed");
} else {
alert("Please select a Radio Button");
}
}
$('.socPlanRadios').find('radio').blur(ValidateRadioButtons);
</script>
I have implemented a different way to do this. 我已经实现了一种不同的方法来实现这一点。 take a look http://jsfiddle.net/gon250/eb4s1k11/
看看http://jsfiddle.net/gon250/eb4s1k11/
code: 码:
$(document).ready(function(){
$('#mybtn').on('click', function(){
var test = $('[name="socPlan"]').is(':checked');
alert(test);
});
});
so you have stored in test
if it's checked or not. 所以如果检查了它,你已经存储在
test
。
Well you are not really on the right path here, you are mixing up stuff. 那么你在这里并没有真正走在正确的道路上,你正在混合东西。 Here is a working fiddle: http://jsfiddle.net/vL9jvwe7/1/
这是一个工作小提琴: http : //jsfiddle.net/vL9jvwe7/1/
$planSelectValid = false;
$('input').click(function () { //Function for Validating If Radio Button isselected
$('.socPlanRadios').find('radio').each(function () { //LoopingthroughradioButtons
if ($(this).is(':checked')) {
$planSelectValid = true;
}
});
if ($planSelectValid = true) {
alert("Validation Passed");
} else {
alert("Please select a Radio Button");
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.