If all three radio buttons are false, don't validate - javascript

I have three different blocks of code, with radio buttons.
The only thing that changes are id and the name of them.
What I need is: if all radio buttons are checked on the value="false" (the user choose to check all the "no"), the form won't be valid.
I'm currently using jQuery validation and all I got to have is that radio buttons are all required.
I tried with this code, but it's not working.
registerForm.validate({
rules: {
'data': {
required: {
depends: function() {
return $('.yesandno').is(':checked').val() === "false";
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="radio" class="yesandno" id="yes-balance" tabindex='9' name="data" value="true" />
<label for="yes-balance" class="yes">YES</label>
<input type="radio" class="yesandno" id="no-balance" tabindex='9' name="data" value="false" />
<label for="no-balance" class="no">NO</label>
</div>
EDIT:
In the end, I mixed Ele's code-reply with the jQuery validation plugin that it is used on the portal I'm working on.
This is the code:
submitHandler: function(form) {
$('#btn-register').click(() => {
if ($('.yesandno:checked[value="false"]').size() === 3) {
return false;
} else {
form.submit();
}
});
}

You could use filter and check the length:
// this filter will only return radios that are checked and have a value of false
$('.yesandno').filter(function() {
return this.checked && this.value === "false";
}).length === 3;

With a jQuery selector you can accomplish that
$('.yesandno:checked[value="false"]').size() === 3
Look at this code snippet
$('button').click(() => {
if ($('.yesandno:checked[value="false"]').size() === 3) {
console.log('All radionbuttos were checked to NO');
} else {
console.log('Either at least one Radionbutto is YES or a (YES/NO) radiobutton was not still checked!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="radio" class="yesandno" id="yes-balance" tabindex='9' name="data" value="true" />
<label for="yes-balance" class="yes">YES</label>
<input type="radio" class="yesandno" id="no-balance" tabindex='9' name="data" value="false" />
<label for="no-balance" class="no">NO</label>
</div>
<div>
<input type="radio" class="yesandno" id="yes-balance" tabindex='9' name="data2" value="true" />
<label for="yes-balance" class="yes">YES</label>
<input type="radio" class="yesandno" id="no-balance" tabindex='9' name="data2" value="false" />
<label for="no-balance" class="no">NO</label>
</div>
<div>
<input type="radio" class="yesandno" id="yes-balance" tabindex='9' name="data3" value="true" />
<label for="yes-balance" class="yes">YES</label>
<input type="radio" class="yesandno" id="no-balance" tabindex='9' name="data3" value="false" />
<label for="no-balance" class="no">NO</label>
</div>
<br>
<button>Click to see selected value!</button>
See? the condition is true when size === 3.

You can check at least one true value to pass your validation instead of checking all three radio buttons for false to fail validation. This will be helpful to scale your HTML radio options without having to change the JQuery code again and again for the length match for false options selection.
function passValidation(){
$('.yesandno').filter(function() {
return this.checked && this.value === "true";
}).length > 0;
}
Call passValidation() function during validation and if it returns true then there is at least one radio button with Yes option selected. And false from passValidation() means no Yes option is selected.

Related

Disable button if one radio is checked

I have three radio each one has name started with delivery_option and a submit button with css class continue. I want to test if a radio is checked the button must be enabled, otherwise it should be disabled.
i made the code below
$(document).ready(function() {
$('#checkout-delivery-step input:radio').each(function() {
if ($("input:radio[name*='delivery_option']:checked").length != 0) {
$('.continue').prop('disabled', false);
} else {
$('.continue').prop('disabled', true);
}
});
});
but it does not work, what was the issue?
You are running the code only once. The code has to be run every time when the radio button is clicked or changed. So you need to use the following:
// Make this a function.
function checkProgress() {
if ($("input:radio[name*='delivery_option']:checked").length != 0) {
$('.continue').prop('disabled', false);
} else {
$('.continue').prop('disabled', true);
}
}
$(function () {
// Set the status once the doc loads.
checkProgress();
// Set it again when any of the radio buttons are clicked.
$("input:radio[name*='delivery_option']").on("click change", checkProgress);
});
Snippet
// Make this a function.
function checkProgress() {
if ($("input:radio[name*='delivery_option']:checked").length != 0) {
$('.continue').prop('disabled', false);
} else {
$('.continue').prop('disabled', true);
}
}
$(function () {
// Set the status once the doc loads.
checkProgress();
// Set it again when any of the radio buttons are clicked.
$("input:radio[name*='delivery_option']").on("click change", checkProgress);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Group 1</h3>
Option 1: <input type="radio" name="delivery_option_1" />
Option 2: <input type="radio" name="delivery_option_1" />
Option 3: <input type="radio" name="delivery_option_1" />
<h3>Group 2</h3>
Option 1: <input type="radio" name="delivery_option_2" />
Option 2: <input type="radio" name="delivery_option_2" />
Option 3: <input type="radio" name="delivery_option_2" />
<p>Submit?</p>
<input type="button" value="Submit" class="continue" disabled />
You can try something like this with removeAttr which will remove the attribute from any element which is already set.
Also, for the radio you can do this way, once it is clicked then you can enable the button because it doesn't provide a way to deselect it.
Finally, the name for elements can be the same if it is a group and only the id must be unique. Check here.
So, proper code will be
<label for="delivery_option1">Option1:</label><input type="radio" id="delivery_option1" name="delivery_option" />
<label for="delivery_option2">Option2:</label> <input type="radio" id="delivery_option2" name="delivery_option" />
<label for="delivery_option3">Option3:</label><input type="radio" id="delivery_option3" name="delivery_option" />
$(function(){
$("input:radio[name*='delivery_option']").click(function(){
$(".continue").removeAttr("disabled");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Option1: <input type="radio" name="delivery_option1" />
Option2: <input type="radio" name="delivery_option2" />
Option3: <input type="radio" name="delivery_option3" />
<input type="button" value="Submit" class="continue" disabled />

How to include a radio-button and a text field in a same if/else function?

I’m new in coding. Maybe it a basics question, but still...
I have a number field which assigns different values to another field with if / else statements, depending on the entered value (number >80 assigns 1, number between 50 and 80 assigns 2 and numbers <50 assigns 3). I have also a radio button, which, if checked, must assign a value (in my case “4”) to the same field and if the radio-button is checked it mustn’t allowed any change trough the number field (4 stays as an assigned value, no matter what number is or will be entered in number field).
Both codes worked separately, but I have a problem to merge them together.
Your help is appreciated.
V
EDIT: I edited the code after the comment from Sumeet, but this doesn’t solve my original question - how to include both in a same if/else statement?
<input id="testscore" type="number" name="testscore">Test score
<br />
<input id="final" type=“text” name="final" readonly="true">Final score class
<br />
<input id="radio1" class="radio" type="radio" name="test" value="4">yes
<input id="radio2" class="radio" type="radio" name="test" value="0">no
<br />
function getFinalScore() {
var testScore = parseFloat($("#testscore").val());
if (testScore >80){
$('#final').val(1);
} else if (testScore <=80 && testScore >50){
$('#final').val(2);
} else {
$('#final').val(3);
}
}
$(document).ready(function() {
$('#testscore').keyup(function(event) {
getFinalScore();
});
});
$('input').click(function(e){
if $("#radio1").is(':checked')){
$("#final").val(4);
} else {
$("#final").val(0);
}
});
You have $(radio1).is(':checked') instead of $("#radio1").is(':checked')
function getFinalScore() {
var testScore = parseFloat($("#testscore").val());
if (testScore >80){
$('#final').val(1);
} else if (testScore <=80 && testScore >50){
$('#final').val(2);
} else {
$('#final').val(3);
}
}
$(document).ready(function() {
$('#testscore').keyup(function(event) {
getFinalScore();
});
});
$('input').click(function(e){
if ($("#radio1"). is(':checked')){
$("#final").val(4);
$('#testscore').prop( "disabled", true );
} else {
$('#testscore').prop( "disabled", false );
$("#final").val(0);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="testscore" type="number" name="testscore">Test score
<br />
<input id="final" type=“text” name="final" readonly="true">Final score class
<br />
<input id="radio1" class="radio" type="radio" name="test" value="4">yes
<input id="radio2" class="radio" type="radio" name="test" value="0">no
<br />
try it: codepen
You can use document.querySelector('#radio1').checked instead $("#radio1").is(':checked')

How to check if all radio buttons (that are rendered) are selected in Jquery/Javascript

I am able to check for all radio buttons that are selected.
However ,I only want to check for those that are rendered (the ones that don't have "display:none").
So if only the 1 and 3 division is selected, it should display true. Currently, it will only display true if all 3 is selected.
EDIT
: I have taken Shree33 answer and made it work with input:radio:visible.
$(document).ready(function() {
$("a").click(function(e) {
e.preventDefault();
var all_answered = true;
$(".division input:radio:visible").each(function() {
var name = $(this).attr("name");
if ($("input:radio[name=" + name + "]:checked").length == 0) {
all_answered = false;
}
});
alert(all_answered);
})
});
.test{
//display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="division">1
<input type="radio" name="radio1" value="false" />
<input type="radio" name="radio1" value="true" />
</div>
<div class="division test">2
<input type="radio" name="radio2" value="false" />
<input type="radio" name="radio2" value="true" />
</div>
<div class="division">3
<input type="radio" name="radio3" value="false" />
<input type="radio" name="radio3" value="true" />
</div>
<div>4
<input type="radio" name="radio4" value="false" />
<input type="radio" name="radio4" value="true" />
</div>
</form>
click
Just use a selector that excludes the non-displayed ones and compare the amount of found elements to the amount of checked radio buttons in that same set (using JQuery context). If the amounts are the same, all visible buttons have been selected.
Also, you really shouldn't use a link when you aren't actually navigating anywhere. If you just need to trigger some code (as is the case here), just about any element can have a click event handler bound to it. By not using an a, you don't have to cancel the native behavior of the link (evt.preventDefault()) and those that rely on assistive technologies, like screen readers won't have problems that occur when the screen reader encounters a link that doesn't actually navigate.
$(function() {
$("#click").click(function(e) {
// Get only the visible DIVs that have the "division" class
var visibleDIVs = $("div.division:not(.hide)");
// Now that we have a collection that contains only the div elements
// that are visible, we can get the count of them easily with: visibleDIVs.length
// We can also search the document for any checked radio buttons, but only those
// that are part of the visible divs collection like this: $("input:radio:checked", visibleDIVs).
// (the second argument (, visibleDIVs) constrains the search for radio buttons to just
// the collection of visilbe divs we've already gotten) and once we have those,
// we can also get the count of them by checking the .length of that collection.
// If the count of visible divs (visibleDIVs.length) equals the count of the visible
// checked radio buttons, then all buttons have been checked:
if(visibleDIVs.length === $("input:radio:checked", visibleDIVs).length){
alert("All Answered");
}
})
});
/* Make the clickable div look like a link */
#click {
text-decoration:underline;
cursor:pointer;
}
.hide { display:none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="division">1
<input type="radio" name="radio1" value="false">
<input type="radio" name="radio1" value="true">
</div>
<div class="division hide">2
<input type="radio" name="radio2" value="false">
<input type="radio" name="radio2" value="true">
</div>
<div class="division">3
<input type="radio" name="radio3" value="false">
<input type="radio" name="radio3" value="true">
</div>
</form>
<div id="click">click</div>
You were close, just change the $("input:radio") selector to $("input:radio:visible"). That should work.
$(document).ready(function() {
$("a").click(function(e) {
e.preventDefault();
var all_answered = true;
$("input:radio:visible").each(function() {
var name = $(this).attr("name");
if ($("input:radio[name=" + name + "]:checked").length == 0) {
all_answered = false;
}
});
alert(all_answered);
})
});
.test{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="division">1
<input type="radio" name="radio1" value="false" />
<input type="radio" name="radio1" value="true" />
</div>
<div class="division test">2
<input type="radio" name="radio2" value="false" />
<input type="radio" name="radio2" value="true" />
</div>
<div class="division">3
<input type="radio" name="radio3" value="false" />
<input type="radio" name="radio3" value="true" />
</div>
</form>
click
Where you're getting the length,
if ($("input:radio[name=" + name + "]:checked").length == 0) {
try
if ($("input:radio[name=" + name + "]:checked").length == 0 && $(this).is(":visible") {
Is that what you are looking for? Also do you need to get the name and concat it, as won't $(this) get you your object as well?
You can check for the parent visible state too:
if (($("input:radio[name=" + name + "]:first").parent().is(':visible')) &&
($("input:radio[name=" + name + "]:checked").length == 0)) {
all_answered = false;
}
https://jsfiddle.net/StepBaro/bLp8wbnh/3/
Pls have a look at this. Seems to solve your "if visible" issue with window.getComputedStyle.

default radio button selection using javascript

Here is what i wanted to accomplish. I have 2 sets of radio buttons. Radio button at the same index position in the 2 sets should not be selected at the same time. If a user tries to select, it must show alert and the defaut radio button must be selected.
Here is my html
<input type="radio" name="A" checked="checked" onclick="return check();" />
<input type="radio" name="A" onclick="return check();" />
<br />
[enter link description here][1]
<input type="radio" name="B" onclick="return check();" />
<input type="radio" name="B" checked="checked" onclick="return check();" />
Here is the JS
function check() {
//logic to check for duplicate selection
alert('Its already selected');
return false;
}
It works perfectly fine. demo
Now suppose, one of the check box is not selected , say in the second set. If the user selects first radio button from second set, which is already selected in the first, an alert is showed. But the radio button remains selected.
Here is modified html
<input type="radio" name="A" checked="checked" onclick="return check();" />
<input type="radio" name="A" onclick="return check();" />
<br />
<input type="radio" name="B" onclick="return check();" />
<input type="radio" name="B" onclick="return check();" />
Here is a demo.
NOTE: i can't use jquery since the code is already a part of some legacy application
To me it seems you should arrange the radio buttons in the other way:
<input type="radio" name="col1" value="A1">
<input type="radio" name="col2" value="A2">
<input type="radio" name="col3" value="A3">
<input type="radio" name="col1" value="B1">
<input type="radio" name="col2" value="B2">
<input type="radio" name="col3" value="B3">
That means the user only can select one value in each column without the obtrusive alert or javascript.
This works without jQuery:
// get all elements
var elements = document.querySelectorAll('input[type="radio"]');
/**
* check if radio with own name is already selected
* if so return false
*/
function check(){
var selected_name = this.name,
selected_value = this.value,
is_valid = true;
// compare with all other elements
for(var j = 0; j < len; j++) {
var el = elements[j];
// does the elemenet have the same name AND is already selected?
if(el.name != selected_name && el.value == selected_value && el.checked){
// if so, selection is not valid anymore
alert('nope')
// check current group for previous selection
is_valid = false;
break;
}
};
return is_valid;
}
/**
* bind your elements to the check-routine
*/
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onmousedown = check;
}
Here is a DEMO
Does this fit your needs?
Give value to your radios:
<input type="radio" name="A" checked="checked" value="1" />
<input type="radio" name="A" value="2" />
<br />
<input type="radio" name="B" value="1" />
<input type="radio" name="B" value="2" />
Then you can do as follows:
var radios = document.querySelectorAll('input[type="radio"]');
for(var i=0;i<radios.length;i++){
radios[i].addEventListener('click', check);
}
function check(){
var index= this.value-1;
if(this.name=='A'){
if(document.getElementsByName('B')[index].checked){
alert('already selectedin other set');
var otherIndex= (index==0)?1:0;
var other = document.getElementsByName("A")[otherIndex];
other.checked= true;
}
}
else{
if(document.getElementsByName('A')[index].checked){
alert('already selected in other set');
var otherIndex= (index==0)?1:0;
var other = document.getElementsByName("B")[otherIndex];
other.checked= true;
}
}
}
check this fiddle

Jquery validation multiple checkbox sets error placement

I have multiple sets of checkboxes.
How can i place the error message to the end of each set of checkboxes.
This code implementation will place the message right after the first element
The fiddle
<form id="myForm" action="">
<input type="checkbox" id="check0" name="check0" class="chkgroup"/>
Set 1 check 1?
<br />
<input type="checkbox" id="check1" name="check1" class="chkgroup"/>
Set 1 check 2?
<br />
<input type="checkbox" id="check2" name="check2" class="chkgroup"/>
Set 1 check 3?
<br />
<br />
<input type="checkbox" id="check3" name="check3" class="chkgroup2"/>
Set 2 check 1?
<br /><input type="checkbox" id="check4" name="check4" class="chkgroup2"/>
Set 2 check 2?
<br /><input type="checkbox" id="check5" name="check5" class="chkgroup2"/>
Set 2 check 3?
<br /><input type="submit" />
Custom method is use to validate the checkbox
$(function () {
jQuery.validator.addMethod("checkboxCheck", function(value, element,params) {
return $(params[0]+':checked').length > 0;
});
$("#myForm").validate({
rules: {
check0:{
checkboxCheck:['.chkgroup'],
},
check3:{
checkboxCheck:['.chkgroup2'],
},
},
messages: {
check0:{
checkboxCheck: "check your checkbox",
},
check3:{
checkboxCheck: "check your checkbox",
},
},
submitHandler: function(form) {
// ajax goes here
alert("valid form");
return false;
}
});
});
You can do that with css float and a div wrapper around each set.
see: http://jsfiddle.net/Xu7ZK/2/

Categories