Javascript radio group by button - javascript

How to display an alert msg when all radio button checked to no? I only know check radio by individual only.
//I only know this method
$('#attraction1').change( function(){
if ($(this).is(':checked')) {
alert('Yes');
}
});
Attraction :
<input type="radio" id="attraction1" name="attraction" value="y" checked/> Yes
<input type="radio" id="attraction2" name="attraction" value="n" /> No
<br>
Individual Attraction :
<input type="radio" id="individual1" name="individual" value="y" checked/> Yes
<input type="radio" id="individual2" name="individual" value="n" /> No
<br>
Plan Board:
<input type="radio" id="planBoard1" name="planBoard" value="y" checked/> Yes
<input type="radio" id="planBoard2" name="planBoard" value="n" /> No

In this case you should check something like this
$('#some_button').click( function(){
if ($('input[type="radio"][value="n"]:checked').length == 3) {
alert('Yes');
}
});

You can use a common class for all radio button with no value and a javascript array every method.
This line const radioNames = [...document.getElementsByClassName('no')]; will get all the radio button with no value ... is spread operator and will convert collection so that array method can be used on that collection.
This line item.addEventListener('change', checkIfAllNo) will attach event change to radio button with value no so that it checks the value for all other radio button
Array method every will return true if all the value in that array satisfies the condition.
So in this line radioNames.every(item => {return item.checked;}); if all the radio button with no value is checked then isAllFalse will be true & the alert will be triggered.
const radioNames = [...document.getElementsByClassName('no')];
function checkIfAllNo() {
const isAllFalse = radioNames.every(item => {
return item.checked;
});
if (isAllFalse) {
alert('All False')
}
}
radioNames.forEach((item) => {
item.addEventListener('change', checkIfAllNo)
})
<input type="radio" id="attraction1" name="attraction" value="y" checked/> Yes
<input type="radio" class="no" id="attraction2" name="attraction" value="n" /> No
<br> Individual Attraction :
<input type="radio" id="individual1" name="individual" value="y" checked/> Yes
<input type="radio" id="individual2" class="no" name="individual" value="n" /> No
<br> Plan Board:
<input type="radio" id="planBoard1" name="planBoard" value="y" checked/> Yes
<input type="radio" id="planBoard2" class="no" name="planBoard" value="n" /> No

In case you have an indeterminate number of inputs you can collect the values for every group and then check if all values match
$("input[type='radio']").change(function() {
// Extract all the radio group names
names = $.unique($('input[type="radio"]').map((v, e) => $(e).attr('name')))
// Collect the value for each group.
// Account for groups that are not selected yet
vals = $.map(names, function(name) {
return $(`input:radio[name="${name}"]:checked`).val() || 'undefined';
})
// Check if collected values match 'n'
console.log(vals.every(v => v == 'n'))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Attraction :
<input type="radio" id="attraction1" name="attraction" value="y" /> Yes
<input type="radio" id="attraction2" name="attraction" value="n" /> No
<br> Individual Attraction :
<input type="radio" id="individual1" name="individual" value="y" /> Yes
<input type="radio" id="individual2" name="individual" value="n" checked/> No
<br> Plan Board:
<input type="radio" id="planBoard1" name="planBoard" value="y" checked/> Yes
<input type="radio" id="planBoard2" name="planBoard" value="n" /> No

#ForeverTwoWheels
Please try this code,To Javascript radio group by button
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Radio Buttons</title>
</head>
<body>
<form>
<input type="radio" name="choice" value="yes"> Yes
<input type="radio" name="choice" value="no"> No
<input type="button" id="btn" value="Show Selected Value">
</form>
<script>
const btn = document.querySelector('#btn');
// handle click button
btn.onclick = function () {
const rbs = document.querySelectorAll('input[name="choice"]');
let selectedValue;
for (const rb of rbs) {
if (rb.checked) {
selectedValue = rb.value;
break;
}
}
alert(selectedValue);
};
</script>
</body>
</html>
I hope this information will be usefull for you.
Thank you.

Related

Verify all radio groups have a value checked using a generic selector

How to Verify all radio groups have at least 1 value selected using a generic selector and the .each() function.
All the examples I find require the id or name of the single radio options to be used not the group.
Try this:
const radios = {};
$('input[type="radio"]').each((i, e) => {
let $radio = $(e);
if ($radio.is(':checked')) {
radios[$radio.attr('name')] = $radio.val();
}
});
console.log(radios);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="radio" value="1" name="ri1">
<input type="radio" value="2" name="ri1" checked="checked">
<input type="radio" value="3" name="ri1">
<input type="radio" value="1" name="ri2">
<input type="radio" value="2" name="ri2">
<input type="radio" value="3" name="ri2" checked="checked">

radio buttons won't check / uncheck

I have some radio buttons in my web page.
when clicking the radio button it checks but when i click again it doesn't un-check.
i tried to add a JS function onclick
document.querySelectorAll('input[type="radio"]').forEach(x => x.addEventListener('click',function(){
if(this.checked == true){
this.checked = false;
}
else {
this.checked = true;
}
}))
when I added this method it allowed my to uncheck but didn't allow me to check any of them!
what can I be missing?
these are my checkboxes:
<input type="radio" id="name" name="name"><br>
<input type="radio" id="age" name="age"><br>
<input type="radio" id="email" name="email"><br>
They all have different name attribute values - therefore they can only be checked (because they're not comparing to another sibling radio value). I think you might be looking for type="checkbox" instead:
<input type="checkbox" id="name" name="name"><br>
<input type="checkbox" id="age" name="age"><br>
<input type="checkbox" id="email" name="email"><br>
Example: Hold down Ctrl (⌘ on mac) key to uncheck.
var radios = document.getElementsByTagName('input');
for(i=0; i<radios.length; i++ ) {
radios[i].onclick = function(e) {
if(e.ctrlKey || e.metaKey) {
this.checked = false;
}
}
}
<input type="radio" name="test" value="1" />
<input type="radio" name="test" value="2" checked="checked" />
<input type="radio" name="test" value="3" />
Use <input type="checkbox", not <input type="radio".
Radio button is used where you have to select one of some options (which must have same name).
For example,
<input type="radio" name="gender" id="male" value="male"> <br>
<input type="radio" name="gender" id="female" value="female"> <br>
<input type="radio" name="gender" id="other" value="other">
Know more about radio button and check boxes.
document.querySelectorAll('input[type="radio"]').forEach(x => x.addEventListener('click',function(){
if(this.value == 0){
this.checked = true;
document.querySelectorAll('input[type="radio"]').forEach(x=>x.value=0);
this.value = 1;
}
else {
this.checked = false;
document.querySelectorAll('input[type="radio"]').forEach(x=>x.value=0);
this.value = 0;
}
}))
<input type="radio" value="0" id="name" name="test"><br>
<input type="radio" value="0" id="age" name="test"><br>
<input type="radio" value="0" id="email" name="test"><br>
This code allows the user to deselect a radio button:
document.querySelectorAll('input[type="radio"]').forEach(x => x.addEventListener('click',function(){
if(! this.value0 || this.value0 == 0){
this.checked = true;
document.querySelectorAll('input[type="radio"][name="'+this.name+'"]').forEach(x=>x.value0=0);
this.value0 = 1;
} else {
this.checked = false;
document.querySelectorAll('input[type="radio"][name="'+this.name+'"]').forEach(x=>x.value0=0);
this.value0 = 0;
}
}))
It improves the answer of Sato Takeru.

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

how to get only one radio button value in javascript

<input type="radio" name="red" value ="red" onclick="myFunction(this.value);"id="chkbx" /> Red<br>
<input type="radio" name="green" value ="green" onclick="myFunction(this.value);"id="chkbx" > green<br>
<input type="radio" name="yellow" value ="yellow " checked onclick="myFunction(this.value);"id="chkbx" > yellow<br>
<input type="radio" name="orange" value ="orange" onclick="myFunction(this.value);"id="chkbx" > orange<br>
<input type="radio" name="blue" value ="blue" onclick="myFunction(this.value);"id="chkbx" > blue<br>
<p id="demo"></p>
button onclick="myfunction(this.value)">My Choice</button>
<br><br>
<p id="demo"></p>
<script>
function myFunction(chkbx)
{
if(chkbx.checked)
{
chkbx.checked = false;
}
else
{
chkbx.checked = true;
}
The Thing is " I want to get the colour from radio button apply to a text in output screen(at a time one radio button would be select).What can i do. Please give some idea. i am new to javascript. I want in javascript only.
.Value will return you the value:
function myFunction(chkbx)
{
if(chkbx.checked)
{
alert(chkbx.value);
}
}
Give all the radio buttons in the group the same name.
Radio buttons allow the user to select only ONE of a predefined set of options. You define groups with the name property (radio buttons with the same name belong to the same group).
So to solve your issue, you can do as belows.
<p><input type="radio" name="color" value ="red"><i>Red</i></p>
<p><input type="radio" name="color" value ="green"><i>Green</i></p>
<p><input type="radio" name="color" value ="yellow" checked><i>Yellow</i></p>
<p><input type="radio" name="color" value ="orange"><i>Orange</i></p>
<p><input type="radio" name="color" value ="blue"><i>Blue</i></p>

How do I get the value of the checked radio button?

I have this simple script attached to a questionnaire and am having a problem getting the selected answer to show up in a textarea. Here is the script:
function check() {
var complete = 0;
var total = 0;
for (i=0;i<document.form.length;i++)
{
if (document.form.elements[i].checked == true && complete < 10) {
complete++;
total = (total) + (Math.round(document.form.elements[i].value));
}
}
if (complete >= 10) {
document.form.message.value = document.form.question1.value;
}
}
And here is the HTML:
<input type="radio" value="1" name="question1" onclick="check()"> A<br />
<input type="radio" value="2" name="question1" onclick="check()"> B<br />
<input type="radio" value="3" name="question1" onclick="check()"> C<br />
<input type="radio" value="4" name="question1" onclick="check()"> D<br />
<input type="radio" value="1" name="question2" onclick="check()"> E<br />
<input type="radio" value="2" name="question2" onclick="check()"> F<br />
<input type="radio" value="3" name="question2" onclick="check()"> G<br />
<input type="radio" value="4" name="question2" onclick="check()"> H<br />
<textarea name="message"></textarea>
I would like the value to be returned, but I am getting undefined. If I alter the line in the script that returns the text to:
document.form.message.value = document.form.question1;
I get [object NodeList]. I know I am missing something so simple but for the life of me I cannot find it.
Also, is it possible I can return the letters A through H along with the value? I know I can replace the value with the letters but need the numbers there for calculations.
My answer is going under the assumption that you would like the <textarea> to be populated with text similar to:
User answered 1 for Question A
User answered 2 for Question F
To get the A or F passed back, I needed to modify your html in the following way:
<input type="radio" value="1" name="question1" onclick="check(this, 'A')"> A<br />
<input type="radio" value="2" name="question1" onclick="check(this, 'B')"> B<br />
<input type="radio" value="3" name="question1" onclick="check(this, 'C')"> C<br />
<input type="radio" value="4" name="question1" onclick="check(this, 'D')"> D<br />
<input type="radio" value="1" name="question2" onclick="check(this, 'E')"> E<br />
<input type="radio" value="2" name="question2" onclick="check(this, 'F')"> F<br />
<input type="radio" value="3" name="question2" onclick="check(this, 'G')"> G<br />
<input type="radio" value="4" name="question2" onclick="check(this, 'H')"> H<br />
<textarea name="message"></textarea>
Otherwise, there's no actual connection between the letter and the radio input.
Anyway, here's what I done did:
I noticed that each group was repeating the same functionality, so I created a single Object Constructor:
var Answer = function () {
this.text = '';
};
this.text will contain the special answer string per group.
Now let's create the two answer group objects:
var answerOne = new Answer();
var answerTwo = new Answer();
Next comes the check() function where we pass the input element as well as it's associated answer character:
var check = function (_input, _question) {
if (_input.name === "question1") {
answerOne.text = "User answered " + _input.value + " for Question " + _question + "\n";
}
if (_input.name === "question2") {
answerTwo.text = "User answered " + _input.value + " for Question " + _question + "\n";
}
document.getElementsByName('message')[0].value = answerOne.text + answerTwo.text;
};
Now, as the user selects an answer, the appropriate answer group's string gets updated accordingly without affecting the other group's answer string.
Here's a jsfiddle with it working: http://jsfiddle.net/smokinjoe/uC76f/13/
Hope that helps!
You are referencing a form element in your script, do you define a form?
The answer seems to be addressed here
Attach event listener through javascript to radio button
Because it's a radio button, you need to loop through all values to find the one that has been selected. Something like this should work:
for (var i=0; i < document.form.question1.length; i++)
{
if (document.form.question1[i].checked)
{
document.form.message.value = document.form.question1[i].value;
}
}
}
Here you go the complete solution.
Couple of things went wrong in your code.
1. The way you get values from radio group. You need to iterate and find out which is checked
2. Setting value to textarea. You need to do getElemenetsByName[x]
<script>
function check() {
var complete = 0;
var total = 0;
var x = document.getElementsByTagName('input');
for(var k=0;k<x.length;k++){
if (x[k].checked && complete < 10) {
complete++;
total = total + Math.round(x[k].value);
}
}
(document.getElementsByName('message')[0]).value = total;
}
</script>
<input type="radio" value="1" name="question1" onclick="check()"> A<br />
<input type="radio" value="2" name="question1" onclick="check()"> B<br />
<input type="radio" value="3" name="question1" onclick="check()"> C<br />
<input type="radio" value="4" name="question1" onclick="check()"> D<br />
<input type="radio" value="1" name="question2" onclick="check()"> E<br />
<input type="radio" value="2" name="question2" onclick="check()"> F<br />
<input type="radio" value="3" name="question2" onclick="check()"> G<br />
<input type="radio" value="4" name="question2" onclick="check()"> H<br />
<textarea name="message"></textarea>
Not tested this, and as I don't know the name (or id) of your form(s), or indeed how many forms you have in your document, I have referenced your form by it's id.
function check() {
var complete = 0;
var total = 0;
var formId = 'EnterYourFormId'; // This could be passed as a paramter to the function instead (e.g. "function check(formId) {")
var _from = document.getElementById(formId); // The form could also be referenced by it's index, e.g. document.forms[0]
for (i=0; i < _from.elements.length; i++) {
if (_from.elements[i].type=='checkbox' && _from.elements[i].checked && complete < 10) {
complete++;
total = total + parseInt(_from.elements[i].value);
}
}
if (complete >= 10) {
_form.message.value = _form.question1.value;
}
}

Categories