Validation of at least one set of radio group - javascript

I have two groups of radio buttons
<input type="radio" name="rb1" value="a">
<input type="radio" name="rb1" value="b">
<input type="radio" name="rb1" value="c">
<input type="radio" name="rb2" value="e">
<input type="radio" name="rb2" value="f">
<input type="radio" name="rb2" value="g">
Now, user:
1. has to select at least one value from either radio groups
2. can select one value from each of the two groups
I need to use javascript for validation. I can validate one or both groups, but how do I check for both?

You want to do something like this...
$('#btnValidate').click(function() {
var v1 = $('input:radio[name="rb1"]:checked').val();
var v2 = $('input:radio[name="rb2"]:checked').val();
if (!v1 && !v2 ) {
alert('not valid');
} else {
alert('valid');
}
});
working jsfiddle here...
http://jsfiddle.net/CEJLt/

Related

How to double click on radiobutton to uncheck instead of one click

I'm using 2 groups of radio buttons lets call it 1.1 1.2 and 2.1 2.1 (one radio button of the second group is always checked, depending on which one of the first group is checked, the other one is hidden).
I can't understand why I need to make a double click on the radio button to uncheck it when both radio buttons are checked. I want to click just one time to "uncheck" it.
function show() {
swich();
}
function swich() {
$('input[type="radio"]').change(function(){
$('[data-group="' + $(this).data('group') + '"]').prop('checked', this.checked);
});
}
var checkedradio = false;
var radioState = [];
$("input[type=radio]").on('click', function(e) {
if (radioState[this.name] === this) {
this.checked = false;
radioState[this.name] = null;
} else {
radioState[this.name] = this;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input data-group="A" id="radio1" required type="radio" value="Yes" name="group1">
<input data-group="B" id="radio2" required type="radio" value="No" name="group1">
<div id="someId1">
<input data-group="A" id="radio3" type="radio" name="group2" value="Yes" onclick="show()">
</div>
<div id="someId2">
<input data-group="B" id="radio4" type="radio" name="group2" value="No" onclick="show()">
</div>
CAVEAT
We do not recommend you take this approach as it breaks the standard UX for radio buttons.
Your issue is because you re-use checkedradio for both checks.
So:
click group A.1 - sets checkedradio = A.1
click group A.1 again, works ok and unchecks
click group A.1 - sets checkedradio = A.1
click group B.1 - sets checkedradio = B.1
click group A.1 (checked) - it's not A.1, so doesn't appear to work, set checkedradio = A.1
click group A.1 2nd time, works ok
You need a different variable for each group.
As multiple variables become very messy very quickly (and lots of DRY), you can use an array:
var radioState = [];
$(":radio").on('click', function(e) {
//console.log(radioState[this.name])
if (radioState[this.name] === this) {
this.checked = false;
radioState[this.name] = null;
} else {
radioState[this.name] = this;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input required type="radio" value="Yes" name="group1">
<input required type="radio" value="No" name="group1">
<hr/>
<input type="radio" name="group2" value="Yes">
<input type="radio" name="group2" value="No">
Code based on this answer expanded to use an array.
I was able to achieve the desired result based on this code.
function show() {
swich();
}
function swich() {
$('input[type="radio"]').change(function(){
$('[data-group="' + $(this).data('group') + '"]').prop('checked', this.checked);
});
}
function toggleRadio(event)
{
if(event.target.type === 'radio' && event.target.checked === true)
{
setTimeout(()=>{ event.target.checked = false; },0);
}
}
document.addEventListener('mouseup', toggleRadio);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input data-group="A" id="radio1" required type="radio" value="Yes" name="group1">
<input data-group="B" id="radio2" required type="radio" value="No" name="group1">
<div id="someId1">
<input data-group="A" id="radio3" type="radio" name="group2" value="Yes" onclick="show(this)">
</div>
<div id="someId2">
<input data-group="B" id="radio4" type="radio" name="group2" value="No" onclick="show(this)">
</div>

How to toggle a radio button with a label

I would like to unselect a radio button when I click on the label and the following code only works as expected if I click on the button itself.
How to link the behaviour of the label to the button?
<label>
<input type="radio" name="choice" value="HTML" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false" /> Learn HTML
</label>
<label>
<input type="radio" name="choice" value="Java" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false"/> Learn JavaScript
</label>
Radio buttons don't work like you are thinking they do. To deselect one you need to either select another with the same name attribute or reset the form. The functionality that you are describing fits more with a checkbox than a radio button. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio for the specs. You may also want to take a look at this question/answer: Reset Particular Input Element in a HTML Form.
Also, there is no need to wrap your label tag around the input. The for attribute takes care of the linking.
If you want to de-select a radio button, you will need to reset the form.
form {
display: flex;
flex-direction: column;
}
<form>
<label for="ckb-01">
<input id="ckb-01" type="radio" name="choice" value="HTML" />
Learn HTML
</label>
<label for="ckb-02">
<input id="ckb-02" type="radio" name="choice" value="Java" />
Learn JavaScript
</label>
<label for="ckb-03">
<input id="ckb-03" type="radio" name="choice" value="Java" />
Learn CSS
</label>
<input type="reset" />
</form>
use the attribut for in the label
<label for='idHTML'>Learn HTML </label>
give the radio the id equivalent
<input id='idHTML' type="radio" name="choice" />
what do you mean by this.__chk
onMouseDown="this.__chk = this.checked"
onClick="if (this.__chk) this.checked = false"
if you wanna select just one you could use simply type radio with group the options with one name='choice'
if you want check and uncheck multiple choices you could use checkbox
After many attempts I finally managed to code a working solution with some javascript.
The problem is that as soon as the radio button is clicked its state changes. the previous value needs to be stored in order to know if it has to be unselected or not.
<main id="form">
<label >
<input type="radio" name="rad" id="Radio0" />Learn Html
</label>
<br><br>
<label>
<input type="radio" name="rad" id="Radio1" />Learn CSS
</label>
<br><br>
<label>
<input type="radio" name="rad" id="Radio2" />Learn Java
</label>
</main>
<script>
let buttons = document.querySelectorAll('#form input');
for (button of buttons){
button.dataset.waschecked="false";
button.addEventListener('click', myFunction, false);
}
function myFunction(e) {
if (e.originalTarget.dataset.waschecked == "false"){
for (button of document.querySelectorAll('#form input')){
button.dataset.waschecked = "false";
}
e.originalTarget.dataset.waschecked = "true";
e.originalTarget.checked =true;
}else {
for (button of document.querySelectorAll('#form input')){
button.dataset.waschecked = "false";
}
e.originalTarget.checked =false;
}
}
</script>
Any suggestion to improve this code is welcome.

weird bug on radio buttons when change [duplicate]

This question already has answers here:
jquery attr('checked','checked') works only once
(2 answers)
Closed 6 years ago.
i'm trying to do a radio button with 2 options: yes and no (is a long form), but in this piece, i need that radio called refused or accomplished be checked when the user choose yes or no, refused and accomplished buttons already are disabled, the user can't change this manually.
1 - when user choose yes: accomplished must be checked
2 - if user choose no, refused must be checked.
3 - if user change the yes to no, or no to yes option we back to the rules 1 or 2 above.
however, i'm stuck because when i change the option the radio button change only once. and nothing happens after that.
this is my code right now: https://jsfiddle.net/bw21cxo5/1/
HTML:
<div>
<label for="yes">
<input type="radio" name="radio1" value="yes" id="yes" class="option-yes">Yes
</label>
<label for="no">
<input type="radio" name="radio1" value="no" id="no" class="option-no">No
</label>
</div>
<br><br>
<div>
<label for="refused">
<input type="radio" name="radio2" id="refused" disabled> Refused
</label>
<label for="accomplished">
<input type="radio" name="radio2" id="accomplished" disabled> Accomplished
</label>
</div>
js: (jquery 2.2)
$('input[name="radio1"]').on('change', function() {
if ($(this).hasClass('option-no')) {
$('#refused').attr('checked', true);
$('#accomplished').attr('checked', false);
} else {
$('#accomplished').attr('checked', true);
$('#refused').attr('checked', false);
}
});
You can associate the checkboxes with each other. Something like this using the data attribute would work:
Updated HTML
<label for="yes">
<input type="radio" name="radio1" value="yes" id="yes" class="option-yes" data-partner="accomplished">Yes
</label>
<label for="no">
<input type="radio" name="radio1" value="no" id="no" class="option-no" data-partner="refused">No
</label>
JavaScript
$('input[name="radio1"]').on('change', function() {
$('input[name="radio2]').prop('checked',false);
$('#'+$(this).data('partner')).prop('checked',true);
});
JS Fiddle: https://jsfiddle.net/igor_9000/bw21cxo5/3/
Hope that helps!
Your code works enough, only a little fix:
$(function () {
$('input[name="radio1"]').on('change', function() {
if ($(this).hasClass('option-no')) {
$('#refused').prop('checked', true);
} else {
$('#accomplished').prop('checked', true);
}
});
});
<script src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
<div>
<label for="yes">
<input type="radio" name="radio1" value="yes" id="yes" class="option-yes">Yes
</label>
<label for="no">
<input type="radio" name="radio1" value="no" id="no" class="option-no">No
</label>
</div>
<br><br>
<div>
<label for="refused">
<input type="radio" name="radio2" id="refused" disabled> Refused
</label>
<label for="accomplished">
<input type="radio" name="radio2" id="accomplished" disabled> Accomplished
</label>
</div>
It's better to use plain JS when checking radio buttons.
Try this:
$('input[name="radio1"]').on('change', function() {
if ($(this).hasClass('option-no')) {
$('#refused').get(0).checked = true;
} else {
$('#accomplished').get(0).checked = true;
}
});
The problem with your code is instead of attr you should have used prop. Here is the difference between them.
Demo

How to do toggle two mutually exclusive radio buttons in HTML

I have two radio buttons. When I click on one, the other should become unchecked, and vice versa.
The code I've produced so far is not working:
<input type="radio" id="rbdemail" onclick="chekrbdclick()" checked="checked" />
<input type="radio" id="rbdsitelnk" onclick="chekrbdclick()" />
function chekrbdclick()
{
// How to manage here?
}
Simple, just use a 'name' property with the same value for both elements:
<html>
<body>
<form>
<input type="radio" name="size" value="small" checked> Small
<br>
<input type="radio" name="size" value="large"> Large
</form>
</body>
</html>
hope it helps
<form>
<label>
<input type="radio" name="size" value="small" checked> Small
</label>
<br>
<label>
<input type="radio" name="size" value="large"> Large
</label>
</form>
Give them a name attribute with common value like size, and it will work. For best practice, you can place your input tag inside a label tag, so that, even if your user clicks on the text beside the button (ie on "Small" or "Large"), the respective radio button gets selected.
The perfect answer is above answered ,but I wanna share you how it can work by javascript ,this is javascript work (not standard answer) ....
<input type="radio" id="rbdemail" onclick="chekrbdclick(0)" checked="checked" value="Small" />Small<br>
<input type="radio" id="rbdsitelnk" onclick="chekrbdclick(1)" value="Large" />Large
<script>
function chekrbdclick(n)
{
var small = document.getElementById('rbdemail');
var large = document.getElementById('rbdsitelnk');
if(n === 0){
small.checked = true;
large.checked = false;
}
else {
small.checked = false;
large.checked = true;
}
}
</script>

Validate multiple choice radio buttons with Javascript

I want to prevent the form ( with id="new_question") from being submitted if an answer (radio button) is not checked from that radio group.
<input class="radioclass" id="q1a" value="a" name="question[q1correct]" type="radio">
<input class="radioclass" id="q1b" value="b" name="question[q1correct]" type="radio">
<input class="radioclass" id="q1c" value="c" name="question[q1correct]" type="radio">
<input class="radioclass" id="q1d" value="d" name="question[q1correct]" type="radio">
<input id="publishbtn" class="greenbtn" type="submit" value="PUBLISH" name="commit"></input>
There are ten radio groups (with the same html above) that require one answer checked.
The form id is "new_question"
So need help making a validation that doesn't allow the form to be submitted unless all the answers are checked.
What I have so far:
validateForm = function() {
x = document.forms['new_question']['question[q1correct]'].value;
if (x === null || x === '') {
alert('Name must be filled out');
return false;
}
};
I do need this for the rest of the 10 radio groups but I think once I know how to do it on one, I can implement the code on all the radio groups.
assuming that kind of html:
<form id="foo">
<div class='selectGroup'>
<input class="radioclass" id="q1a" value="a" name="question[q1correct]" type="radio">1</input>
<input class="radioclass" id="q1b" value="b" name="question[q1correct]" type="radio">2</input>
<input class="radioclass" id="q1c" value="c" name="question[q1correct]" type="radio">3</input>
<input class="radioclass" id="q1d" value="d" name="question[q1correct]" type="radio">4</input>
</div>
<div class='selectGroup'>
<input class="radioclass" id="q2a" value="a" name="question[q2correct]" type="radio">1</input>
<input class="radioclass" id="q2b" value="b" name="question[q2correct]" type="radio">2</input>
<input class="radioclass" id="q2c" value="c" name="question[q2correct]" type="radio">3</input>
<input class="radioclass" id="q2d" value="d" name="question[q2correct]" type="radio">4</input>
</div>
<input id="publishbtn" class="greenbtn" type="submit" value="PUBLISH" name="commit">
</input>
</form>
you might use following js
$('#foo').submit(function(e) {
e.preventDefault();
var $form = $(e.currentTarget)
var groupsValidationList = []
selectGroups = $form.children('.selectGroup')
selectGroups.each(function(index, group) {
$group = $(group);
checks = $group.children('.radioclass').map(function(index, radioItem) {
return $(radioItem).is(':checked')
})
isValid = ($.inArray(true, checks) != -1);
groupsValidationList.push(isValid);
})
if(groupsValidationList.every(function(validationResult) { return validationResult; })) {
alert('ok');
} else {
alert('at least one group is not marked');
}
})
https://jsfiddle.net/4qwvgqkz/

Categories

Resources