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

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>

Related

Radio button second click makes uncheck

If my radio button previously checked and i try to uncheck with second click i have to click once more. So it means if my radio button previously checked i got to clicked 2 times for unchecked but it should works with only 1 click . How can i fix it. Here is 2 codes they both have the same issue. I show both scripts here .Thanks For Helping!
$(function(){
$('input[name="rad"]').click(function(){
var $radio = $(this);
// if this was previously checked
if ($radio.data('waschecked') == true)
{
$radio.prop('checked', false);
$radio.data('waschecked', false);
}
else
$radio.data('waschecked', true);
// remove was checked from other radios
$radio.siblings('input[type="radio"]').data('waschecked', false);
});
});
$("input:radio").on("click", function (e) {
var inp = $(this);
if (inp.is(".clicked")) {
inp.prop("checked", false).removeClass("clicked");
} else {
$("input:radio[name='" + inp.prop("name") + "'].clicked").removeClass("clicked");
inp.addClass("clicked");
}
});
<input type="radio" name="rad" id="Radio0" checked="checked"/>
<input type="radio" name="rad" id="Radio1" />
<input type="radio" name="rad" id="Radio2" />
<input type="radio" name="rad" id="Radio4" />
<input type="radio" name="rad" id="Radio3" />
and here is my html and jsfiddle
http://jsfiddle.net/fbyg1htz/
http://jsfiddle.net/7g684219/
The input element which is selected by default (checked="checked") should have the waschecked data attribute set to true because it's already checked.
<input type="radio" name="rad" id="Radio0" data-waschecked="true" checked="checked"/>
And the same for the second example. You should add class="clicked" to the element that is initially checked.
<input type="radio" name="rad" id="Radio0" class="clicked" checked="checked"/>
Updated fiddles:
http://jsfiddle.net/6fqLexbr/
http://jsfiddle.net/rmuh1sz3/
Example with razor for your first script:
<input type="radio" id="status_active" value="true" asp-for="ActiveOrPassive"
data-waschecked="#Model.OrderFilter.ActiveOrPassive.ToString().ToLower()" />
and for your second script:
<input type="radio" id="status_active" value="true" asp-for="ActiveOrPassive"
class="#(Model.OrderFilter.ActiveOrPassive ? "clicked" : null)" />

Is there way to click multiple checkboxes when a option(check box) is on and when it is off you can only select one at a time?

I want to be able to perform the functionality in the picture above. It wont work however.
$("#customSwitches").click(function() {
var $this = $(this);
if ($this.data('clicked')) {
alert("not element clicked");
$this.data('clicked', false);
$(document).on('click', "#radio1, #radio2, #radio3, #radio4").not(this).prop('checked', false);
});
} else {
alert("element clicked");
$this.data('clicked', true);
}
});
In each click of the check box from the groups, you can checked the checked property of #customSwitches. If it is not checked then you can count the length of checked check boxes from the group, if it is more than 1 then you can prevent the default event.
When clicking #customSwitches you can reset all the check boxes from the group.
You can try the following way:
$(".vehicle").click(function(e){
if($('#customSwitches').is(':not(:checked)')){
if($('.vehicle:checked').length > 1){
alert('You can not check multiple');
e.preventDefault();
}
}
});
$("#customSwitches").click(function(e){
$(".vehicle").prop('checked', false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="customSwitches"> Select Multiple</label><input type="checkbox" id="customSwitches">
<hr/>
<input class="vehicle" type="checkbox" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label>
<input class="vehicle" type="checkbox" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label>
<input class="vehicle" type="checkbox" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label>
Your current code has some syntax issues and uses nested event handlers, which is not a good design pattern.
In basic terms you are trying to build a dynamic checkbox limiter based on the first checkbox state. To do that simply determine if the first box is checked, and then count the number of checked regions to see if it exceeds the limit. If so, disallow the current box to be checked. Try this:
let $allowMulti = $('#allow_multi').on('change', function() {
if (!this.checked)
$('.region').prop('checked', false); // remove all checks if no multi allowed
});
$('.region').on('change', function() {
let selectedCount = $('.region:checked').length;
if (!$allowMulti.prop('checked') && selectedCount > 1)
$(this).prop('checked', false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
<label>
<input type="checkbox" id="allow_multi">
Select multiple regions
</label>
</p>
<label>
<input type="checkbox" class="region" value="1"> 1
</label>
<label>
<input type="checkbox" class="region" value="2"> 2
</label>
<label>
<input type="checkbox" class="region" value="3"> 3
</label>
<label>
<input type="checkbox" class="region" value="4"> 4
</label>

Radio button change events and improving similar functions

I'm looking for a smarter way to reuse functions with a similar purpose. For example I would want to change different radio buttons that toggle a hide class on different divs.
JSFiddle Link
How would you mathe JQuery to a reusable function,
<form>
<label>Enable One</label>
<input type="radio" name="one" value="yes" checked class="eOne">Yes
<input type="radio" name="one" value="no" class="enBg">No</form>
<form>
<label>Enable Two</label>
<input type="radio" name="two" value="yes" checked class="eTwo">Yes
<input type="radio" name="two" value="no" class="enBrand">No</form>
<form>
<label>Enable Three</label>
<input type="radio" name="three" value="yes" checked class="eThree">Yes
<input type="radio" name="three" value="no" class="enS">No</form>
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
div {
width: 100px;
height: 100px;
}
.one {
background: red;
}
.two {
background: green;
}
.three {
background: blue;
}
.hide {
display: none;
}
$(".eOne").change(function () {
$('.one').toggleClass("hide");
});
$(".eTwo").change(function () {
$('.two').toggleClass("hide");
});
$(".eThree").change(function () {
$('.three').toggleClass("hide");
});
Also, for some reason, in the demo (but not in my live version) the change function doesn't toggle the class unless I click no and then yes.
use classes for your html:
<form>
<label>Enable One</label>
<input type="radio" name="one" value="yes" class="one" checked />Yes
<input type="radio" name="one" value="no" class="one" />No
</form>
<form>
<label>Enable Two</label>
<input type="radio" name="two" value="yes" class="two" checked />Yes
<input type="radio" name="two" value="no" class="two" />No
</form>
<div class="one"></div>
<div class="two"></div>
write functions for your javascript:
/*
* Bind a change event handler to a radio-input
* #param cls - selector string to input AND to-change div
*/
function bindChangeHandler(cls) {
$('input.' + cls).change(function () {
var element = $(this),// get Input element
name = element.val(), // get Input element name
is_checked = element.prop('checked'); // get state of radio box
// return if a deselect triggered the event (may be unnecessary)
if (!is_checked) return;
// change class of div-box according to checked radio-box
if (name == 'yes') {
$('div.' + cls).removeClass('hide');
} else {
$('div.' + cls).addClass('hide');
}
});
}
$(document).ready(function(){
bindChangeHandler('one');
bindChangeHandler('two');
});
HTML
<form>
<label>Enable One</label>
<input type="radio" name="one" value="yes" class="eOne" checked>Yes
<input type="radio" name="one" value="no" class="enBg">No
<br /><label>Enable Two</label>
<input type="radio" name="two" value="yes" checked class="eTwo">Yes
<input type="radio" name="two" value="no" class="enBrand">No
<br /><label>Enable Three</label>
<input type="radio" name="three" value="yes" checked class="eThree">Yes
<input type="radio" name="three" value="no" class="enS">No
</form>
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
I haven't changed any of your CSS but changed your Javascript code. Have a look at this.There is no need to use the class .hideclass as we have already an inbuilt method for this. the toggle() method. if you want it to hide as soon as you click the radio button then just change all the toggle() to toggle(50). This change will hide the div boxes in just 50 milli seconds.
$("input[name='one']").change(function(){
$(".one").toggle();//add a number in toggle method to have a small animation effect :)
});
$("input[name='two']").change(function(){
$(".two").toggle();
});
$("input[name='three']").change(function(){
$(".three").toggle();
});
I have also updated the code on js fiddle. May be this is helpful for you :)
I like cbergmiller's answer. Here is the same rewritten with a callback allowing a more general use:
function hide(cls, name) {
// change class of div-box according to checked radio-box
if (name == 'yes') {
$('div.' + cls).removeClass('hide');
} else {
$('div.' + cls).addClass('hide');
}
}
/*
* Bind a change event handler to a radio-input
* #param cls - selector string to input AND to-change div
*/
function bindChangeHandler(cls, callback) {
$('input.' + cls).change(function () {
var element = $(this),// get Input element
name = element.val(); // get Input element name
callback(cls, name);
});
}
$(document).ready(function(){
bindChangeHandler('one', hide);
bindChangeHandler('two', hide);
});

Validation of at least one set of radio group

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/

jquery: how to check if all radio buttons in a div are selected

my html looks like this
<div id="div1">
<input type="radio" name="r1" value="v1" />
<input type="radio" name="r1" value="v2" />
<input type="radio" name="r1" value="v3" />
<input type="radio" name="r2" value="v1" />
<input type="radio" name="r2" value="v2" />
<input type="radio" name="r2" value="v3" />
<input type="radio" name="r3" value="v1" />
<input type="radio" name="r3" value="v2" />
<input type="radio" name="r3" value="v3" />
</div>
radio buttons are dynamically generated on my html so in that div i don't know how many radio buttons i have.
i want to make sure that the user will select a value for each one of them before he submits the form, how can i check that all radio buttons inside my div has a value checked?
Thank you
$(":radio").change(function() {
var names = {};
$(':radio').each(function() {
names[$(this).attr('name')] = true;
});
var count = 0;
$.each(names, function() {
count++;
});
if ($(':radio:checked').length === count) {
alert("all answered");
}
}).change();
Demo: http://jsfiddle.net/yFaAj/15/
Restructure your HTML slightly - wrap each radio group in (say) a div. Then you can just do something like this to validate the form when the user submits it:
if ($('div:not(:has(:radio:checked))').length) {
alert("At least one group is blank");
}
Of course this can be tweaked in various ways to suit your HTML. The idea was from Find all radio groups which haven't been selected
Solution here http://jsfiddle.net/QxdnZ/1/
var checked = $("#div1 :radio:checked");
var groups = [];
$("#div1 :radio").each(function() {
if (groups.indexOf(this.name) < 0) {
groups.push(this.name);
}
});
if (groups.length == checked.length) {
alert('all are checked!');
}
else {
var total = groups.length - checked.length;
var a = total>1?' groups are ':' group is ';
alert(total + a + 'not selected');
}
Validate the form when the user submits it, using this validation code.
var blank = false;
$("input:radio").each(function() {
var val = $('input:radio[name=' + this.name + ']:checked').val();
if (val === undefined) {
blank = true;
return false;
}
});
alert(blank ? "At least one group is blank" : "All groups are checked");
First we get the names of all the radio button groups, then check that each one has a value. (Actually we're doing multiple checks, but that doesn't really matter.)
Looking for something along these lines? http://jsfiddle.net/gXsZp/3/
<div id="div1">
Q1
<input type="radio" name="r1" value="v1" />
<input type="radio" name="r1" value="v2" />
<input type="radio" name="r1" value="v3" />
<br/>Q2
<input type="radio" name="r2" value="v1" />
<input type="radio" name="r2" value="v2" />
<input type="radio" name="r2" value="v3" />
<br/>Q3
<input type="radio" name="r3" value="v1" />
<input type="radio" name="r3" value="v2" />
<input type="radio" name="r3" value="v3" />
</div>
<br/>
<input id="btn" type="submit" text="submit"/>
$('#btn').click(function(){
if ( $('#div1 input:radio:checked').size() == 3 )
return true;
return false;
});
Try this one:
$('input:radio', $('#div1')).each(function() {
if(name && name == $(this).attr('name'))
return true; // Skip when checking the same element name.
name = $(this).attr('name');
if(! $('input:radio[name="' + name + '"]:checked').length) {
alert('Oops, you missed some input there.. [' + name + ']');
return false;
}
});
It will loop through every radio button to check for checked radio & will break as soon it found non-checked radio group (first error found). But if you prefer to get all the errors (not only the first error found), just remove return false.
Try this:
function check(){
var allCheck = true;
if($("#div1 :radio:checked").length==0){
allCheck=false;
}
$("#div1 :radio").each(function(){
for(var i=0;i<$("#div1 :radio:checked").length;i++)
if($(this).attr("name")===$($("#div1 :radio:checked")[i]).attr("name"))
break;
else if(i==$("#div1 :radio:checked").length-1)
allCheck = false;
});
return allCheck;
}
This will work:
if($("#div1").children("input:radio:checked").size() == 3)
{
alert('three inputs were checked');
}

Categories

Resources