radio button enable/disable not working as expected - javascript

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);
}
});
});

Related

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.

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.

How to add the checked input box in input text whether onload or onclick using jquery

Im getting the result now, but what I want is to Also get the checked input box and put into the input text not just only using on change event in jQuery but also on page loads. As you can see, one of the checkboxes below has been checked but not putting into the input text. Please see my code below:
$(document).ready(function(){
$checks = $(":checkbox");
$checks.on('change', function() {
var string = $checks.filter(":checked").map(function(i,v){
return this.value;
}).get().join(",");
$('#field_results').val(string);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="multiple">
<input type="text" id="field_results"/><br>
<input type="checkbox" value="1" checked>1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
</div>
<div class="multiple">
<input type="text" id="field_results"/><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2" checked>2<br>
<input type="checkbox" value="3">3
</div>
You can do this easily like:
$(document).ready(function() {
$checks = $(":checkbox");
$checks.on('change', setResults);
function setResults() {
var string = $checks.filter(":checked").map(function(i, v) {
return this.value;
}).get().join(",");
$('#field_results').val(string);
}
setResults();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="field_results" /><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2" checked>2<br>
<input type="checkbox" value="3" checked>3
You should set values into input at first, try this:
$(document).ready(function() {
$checks = $(":checkbox");
$('#field_results').val(getCheckedValues());
$checks.on('change', function(){
$('#field_results').val(getCheckedValues());
});
});
function getCheckedValues(){
$checks = $(":checkbox");
var valuse = $checks.filter(":checked").map(function(i, v) {
return this.value;
}).get().join(",");
return valuse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="field_results"/><br>
<input type="checkbox" value="1" checked>1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3" checked>3<br>
<input type="checkbox" value="4">4<br>
<input type="checkbox" value="5" checked>5<br>
The easiest way to do it You can use .trigger() to set default value
$checks.trigger('change');

How to make checkbox readonly

I have a form with with two fields one is radio button and second one is checkbox. I want to make checkbox unchecked(If checked) and readonly when radio button value is No. My code is working for unchecked functionality but readonly does not work.Please help me
This is my code:
Html :
<input type="radio" name="data[User][email_status]" id="" value="yes">Yes
<input type="radio" name="data[User][email_status]" id="" value="no" checked="checked">No
<input type="checkbox" name="data[User][no_alerts]" id="" value="yes">
Jquery code :
$(document).ready(function() {
$('input[name="data[User][email_status]"]').change (function(){
//console.log($(this).val());
if ($(this).val() == 'no') {
$('input[name="data[User][no_alerts]"]').attr({
'checked' : false,
});
}
});
});
Thanks
Use the disabled property to make the input readonly
$('input[value="no"]:checked').next().prop("disabled", true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="data[User][email_status]" id="" value="yes">Yes
<input type="radio" name="data[User][email_status]" id="" value="no" checked="checked">No
<input type="checkbox" name="data[User][no_alerts]" id="" value="yes">
or a more general approach
$('input[value="no"]:checked').parent().find('input[type="checkbox"]').prop("disabled", true);
$('input[name="data[User][no_alerts]"]').attr({
'disabled' : true,
});
You may like this code snippet:
$(function() {
var chk = $('input[name="data[User][no_alerts]"]');//got check-box
$('input[name="data[User][email_status]"]').on('change', function(e) {
chk.prop('disabled', false); //enable first
if ('no' == this.value) {
chk.prop({
'disabled': true,
'checked': false
});
}
});
$('input[name="data[User][email_status]"]:checked').trigger('change');//fire code on page load
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="data[User][email_status]" id="" value="yes">Yes
<input type="radio" name="data[User][email_status]" id="" value="no" checked="checked">No
<input type="checkbox" name="data[User][no_alerts]" id="" value="yes">
this can also be used
$('input[name="data[User][email_status]"]').change (function(){
//console.log($(this).val());
if ($(this).val() == 'no') {
$('input[name="data[User][no_alerts]"]').attr({
'checked' : false,
'disabled':"disabled",
});
}
});

How to grey out other radio buttons after one is selected until refresh

Hopefully somebody can prompt me into the right direction,
I want a simple 3 radio button form, lets say 1,2,3
once 1 has been selected i want to disable options 2 and 3 until page has been refreshed
so maybe those option would grey out and not be selectable
any help appreciated cant find a thing on google
We will group radio buttons in a div:
<div class="readioBtnDiv">
<input type="radio" name="group1" value="1" />1
</div>
<div class="readioBtnDiv">
<input type="radio" name="group2" value="1" />2
</div>
<div class="readioBtnDiv">
<input type="radio" name="group3" value="1" />3
</div>
Now we will disable another radio button when one is selected:
$("input:radio").click(function() {
var $this = $(this);
var value = $this.val();
$this.closest('.readioBtnDiv')
.siblings('.readioBtnDiv')
.find('input:radio[value="' + value + '"]')
.attr("disabled","disabled");
});
Here we go, jQuery way:
HTML:
<form>
<input type="radio" value="1"> 1
<input type="radio" value="2"> 2
<input type="radio" value="3"> 3
</form>
JS:
<script>
$('input').on('click', function() {
$(this).parent().find('input:not(:checked)').attr( "disabled", "disabled" );
})
</script>
To add jQuery to your project - simply insert
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
inside your <head> </head> tag.
UPDATE:
To keep it after page refreshes you should modify your code to this:
<form>
<input type="radio" value="1" id="radio1"> 1
<input type="radio" value="2" id="radio2"> 2
<input type="radio" value="3" id="radio3"> 3
</form>
<script>
$('#'+localStorage.selected).trigger('click');
$('#'+localStorage.selected).parent().find('input:not(:checked)').attr( "disabled", "disabled" );
$('input').on('click', function() {
$(this).parent().find('input:not(:checked)').attr( "disabled", "disabled" );
localStorage.setItem('selected', $(this).attr('id'));
})
</script>
I think all the answers are right and accurate to your question above but according to me you would find this answer more useful and understandable if you are newbie
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
function myFunction1() {
document.getElementById("radio2").disabled = true;
document.getElementById("radio3").disabled = true;
}
function myFunction2() {
document.getElementById("radio1").disabled = true;
document.getElementById("radio3").disabled = true;
}
function myFunction3() {
document.getElementById("radio2").disabled = true;
document.getElementById("radio1").disabled = true;
}
</script>
</head>
<body>
<div class="block">
<input onclick="myFunction1();" type="radio" id="radio1" value="Radio1" /><label>Radio1</label>
<input onclick="myFunction2();" type="radio" id="radio2" value="Radio2" /><label>Radio2</label>
<input onclick="myFunction3();" type="radio" id="radio3" value="radio3" /><label>radio3</label>
</div>
</body>
</html>
It's a working example according to your need. Cheers :)

Categories