radio buttons won't check / uncheck - javascript

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.

Related

Javascript radio group by button

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.

Javascript querySelector get value condition

I am trying to get value from input radio button with querySelector, but I want to write condition "if input is checked = console log is input value, but if input is not checked = console log is 0"
My code is:
function getVal(){
var firstVal= document.querySelector("input[name='price1']:checked");
if (firstVal.checked){
console.log(firstVal.value);
}
}
If i call function getVal now i get value from checked input.
but i tried to write this :
function getVal(){
var firstVal= document.querySelector("input[name='price1']:checked");
if (firstVal.checked){
console.log(firstVal.value);
} else
console.log(0);
}
}
but program not working console log shows nothing.
Then i tried
function getVal(){
var firstVal= document.querySelector("input[name='price1']:checked");
if (firstVal.checked){
console.log(firstVal.value);
}
if (firstVal.checked === false){
console.log(0);
}
}
And still program not working. Console log shows nothing.
My HTML code is:
<label for="test1">test1</label>
<input type="radio" name="price1" id="test1" value="1" onchange="showPrice();">
<label for="test2">test2</label>
<input type="radio" name="price1" id="test2" value="2" onchange="showPrice()">
<label for="test3">test3</label>
<input type="radio" name="price1" id="test3" value="3" onchange="showPrice()">
<label for="test4">test4</label>
<input type="radio" name="price1" id="test4" value="4" onchange="showPrice()">
</div>
Edit
I use querySelectorAll and I fixed it.
If is not checked input radio, value in console is 0.
If is checked input radio, you get value from checked radio.
Here is my new code
function getVal() {
var firstVal = document.querySelectorAll("input[name='price1']");
if (firstVal[0].checked){
console.log(firstVal[0].value);
}
if (firstVal[1].checked){
console.log(firstVal[1].value);
}
if (firstVal[2].checked){
console.log(firstVal[2].value);
}
if (firstVal[3].checked){
console.log(firstVal[3].value);
}
if(firstVal[0].checked === false && firstVal[1].checked === false && firstVal[2].checked === false && firstVal[3].checked === false){
console.log(0);
}
}
<button onclick="getVal()">test</button><div class="priceInput">
<label for="test1">test1</label>
<input type="radio" name="price1" id="test1" value="1">
<label for="test2">test2</label>
<input type="radio" name="price1" id="test2" value="2">
<label for="test3">test3</label>
<input type="radio" name="price1" id="test3" value="3">
<label for="test4">test4</label>
<input type="radio" name="price1" id="test4" value="4">
But still I dont understand why I didnt get value with this code:
function getVal(){
var firstVal= document.querySelector("input[name='price1']:checked");
if (firstVal.checked){
console.log(firstVal.value);
}
if (firstVal.checked === false){
console.log(0);
}
}
Thank for help guys. Herectic Monkey solved it.
Final code:
function getVal(){
var firstVal= document.querySelector("input[name='price1']:checked");
if (firstVal) {
console.log(firstVal.value);
} else {
console.log(0);
}
}
You can achive it using jQuery very simple,
$('.test').change(function(){
var isChecked = $(this).is(':checked');
console.log(isChecked ? $(this).val() : 0);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="test1">test1</label>
<input type="checkbox" name="test1" class="test" value="1">
<label for="test2">test2</label>
<input type="checkbox" name="test2" class="test" value="2">
<label for="test3">test3</label>
<input type="checkbox" name="test3" class="test" value="3">
<label for="test4">test4</label>
<input type="checkbox" name="test4" class="test" value="4">

Check the value of radiobutton

I am trying to see on console that which radio button is selected.There are two radio buttons.I get this error TypeError: document.getElementById(...) is null Should I use checked feauture instead of value?
<input required="required" class="form-radio" id="edit-1" name="submitted[315]" value="1" type="radio">
<input required="required" class="form-radio" id="edit-2" name="submitted[315]" value="2" checked="checked" type="radio">
var y=document.getElementById('edit-2').value;
if(y == 2)
{
console.log("no");
} else{
console.log("yes");
}
Make sure the field wich id="edit-2" exists when your script is executed.
Otherwise, use document.ready function like :
document.addEventListener("DOMContentLoaded", function(event) {
var y=document.getElementById('edit-2').value;
if(y == 2){
console.log("no");
} else{
console.log("yes");
}
});
seems to work like this:
var y = document.getElementById('edit-2').checked;
if(y) {
console.log("no");
} else{
console.log("yes");
}
<input required="required" class="form-radio" id="edit-1" name="submitted[315]" value="1" type="radio">
<input required="required" class="form-radio" id="edit-2" name="submitted[315]" value="2" checked="checked" type="radio">
Use checked instead of value when the radio buttons are not in a form.
var checkSelection = function () {
if(document.getElementsByClassName('form-radio')[0].checked)
{
console.log("yes");
}
else {
console.log("no");
}
}
<input required="required" class="form-radio" name="submitted[315]" type="radio"> Yes
<input required="required" class="form-radio" name="submitted[315]" type="radio" checked="checked"> No
<button onClick="checkSelection()">Check Selection</button>

radio button enable/disable not working as expected

I am trying to switch my radio buttons either true or false using the following functionality.
But as a first click, I am not getting any response. Later on it works fine. ow to solve this issue and what is wrong here?
var switching = false;
$('button').on("click", function() {
switching = switching == false ? switching = true : switching = false;
console.log("switching", switching); //first click true but not works!
$(":radio").attr("disabled", switching);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="foo" value="Y" checked disabled>
<input type="radio" name="foo" value="N" disabled>
<input type="radio" name="foo" value="X" disabled>
<button>
Switch Me
</button>
Live Demo
You can just start from true and switch like this switching = !switching
var switching = true;
$('button').on("click", function() {
switching = !switching
$(":radio").attr("disabled", switching);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="foo" value="Y" checked disabled>
<input type="radio" name="foo" value="N" disabled>
<input type="radio" name="foo" value="X" disabled>
<button>
Switch Me
</button>
Or you can do it just with one line:
$('button').on("click", function() {
$(":radio").prop('disabled', function(){ return !this.disabled });
});
button.border { border:2px solid green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="foo" value="Y" checked disabled>
<input type="radio" name="foo" value="N" disabled>
<input type="radio" name="foo" value="X" disabled>
<button>Switch Me</button>
Your ternary operator is incorrect it should be :
switching = switching == false ? true : false;
so your code becomes :
var switching = false;
$('button').on("click", function(){
switching = switching == false ? true : false;
console.log( "switching", switching );
$(":radio").attr("disabled", switching);
})
but the first click will not work with this so you need to initialize it as true.
var switching = true;
$('button').on("click", function(){
switching = switching == false ? true : false;
console.log( "switching", switching );
$(":radio").attr("disabled", switching);
})
button.border{
border:2px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="foo" value="Y" checked disabled>
<input type="radio" name="foo" value="N" disabled>
<input type="radio" name="foo" value="X" disabled>
<button>
Switch Me
</button>
You can also check first whether is disable or not
$('button').on("click", function() {
if ($(":radio").prop('disabled')){
$(":radio").attr("disabled", false);
}
else
{
$(":radio").attr("disabled", true);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="foo" value="Y" checked disabled>
<input type="radio" name="foo" value="N" disabled>
<input type="radio" name="foo" value="X" disabled>
<button>
Switch Me
</button>
Add a common class in your HTML :
<input type="radio" name="foo" value="Y" checked disabled class="radio">
<input type="radio" name="foo" value="N" disabled class="radio">
<input type="radio" name="foo" value="X" disabled class="radio">
<button>
Switch Me
</button>
Now Here is your JS using class
$( document ).ready(function() {
$('button').on("click", function(){
if($('.radio').is(':enabled')) {
$(".radio").attr("disabled", true);
}else {
$(".radio").attr("disabled", false);
}
});
});

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

Categories