Selected multiple radio buttons when condition is met - javascript

So I have this selection list with radio buttons that looks like this:
What I try to do is when 'AT' is selected I Want to be able to select 1 more option.
for example if 'AT' is checked I also want to be able to check 'Herstart'.
so this condition only needs to happen when 'AT' is selected.
this is a picture of the console on how the radio buttons are build :
I was thinking on something like if(data-status =="AT"){ allow to check one more radio button}
but here I am stuck on what to write in the if block.
this is also not my code so it's even harder to come with a solution.
anyone can point me in the right direction ?
kind regards

you can't select multiple radio buttons, to select multiple we use checkboxes, learn here the difference between checkbox and radio more
here is the working with checkbox:
$(document).ready(function() {
$('.checked').on('change', function() {
var x = $("#check3").is(':checked');
if (x) {
$('#check1').prop('checked', (x));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input type="checkbox" class="checked" id="check1">hertstart
<input type="checkbox" class="checked" id="check2">uti,nsa
<input type="checkbox" class="checked" id="check3">AT

Radio buttons are meant to be single choice only. If you need to have more than one option available, use checkboxes. These you can toggle active/disabled with the disabled property and javascript.

Related

How do i uncheck radio button in one click

I have the code to uncheck radio button, but the problem is, its not happening in one click when the radio button is checked, I am fetching the value of radio button as checked from mysql, so the default value of radio button is checked and when I click on the radio button the value should uncheck upon single click but my code is making it happen on double click. How do I make it happen with single click?
var check;
$('input[type="radio"]').hover(function() {
check = $(this).is(':checked');
});
var checkedradio;
function docheck(thisradio) {
if (checkedradio == thisradio) {
thisradio.checked = false;
checkedradio = null;
}
else {checkedradio = thisradio;}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="check" value="check" onClick="javascript:docheck(this);" checked="checked"/>
Radios by design are meant to be used in a group (https://html.spec.whatwg.org/#radio-button-state-(type=radio)) - a group of 2 or more radios should form a group to allow the user to pick a value from the selection in that group. By design the radio group behaviour is this - once a selection is made (either by the user or programatically), that choice sticks, and there is no way to undo it, other than choose another radio option from the group. You'll see in your example, that without the JavaScript bit, if you by default uncheck the radio, then check it manually, you won't be able to uncheck it again. This is how it's supposed to work.
The rule of thumb should be that solving a problem on the backend should not come at the expense of the front-end, as it negatively impacts the user-experience, and will cause problems to the user. If you for any reason HAVE TO stick with such a bad UX solution, here is a way to hack your radio to act like a checkbox, but it is seriously not advised, and you should change your backend to use checkboxes instead.
Here is the radio hack (and a native checkbox input that should be used instead):
var myRadio = $('input[type="radio"]:checked');
myRadio.on('click', function() {
if (myRadio.attr('checked')) {
myRadio.removeAttr('checked');
myRadio.prop('checked', false);
} else {
myRadio.attr('checked', 'checked');
myRadio.prop('checked', true);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<b>This works, but it's bad UX, so avoid!</b><br>
<input type="radio" name="check" value="check" checked />
<hr>
<b>Use this instead!</b>
<br>
<input type="checkbox" name="real-check" value="real-check" checked />
You'll see that the jQuery selector is deliberately set to only pick the "checked" radio, so the JavaScript solution only takes over the native behaviour if the radio is checked by default. As soon as the radio is not checked by default, you'll see how the browser forces your selection once it's checked manually - this is a tell tale sign that you're trying to deviate from the expected behaviour.
You'll also see that the checkbox natively works - without the need for JavaScript or jQuery.
RobertP raised an interesting point about the user experience, or in IT-talk: "UX". In some cases it is mandatory that a single option needs to be clicked. This is exactly what radio buttons were made for. However, I have come across cases, where a "none" selection should also be offered. For these cases you could simply supply an extra radio button with the option "none" OR you could make the radio buttons "unselectable" again. This seems to go against the intended radio button behaviour. However, as it is possible to start out with no radio buttons being selected, why should it not be possible to return to this state after, maybe, the user had clicked on an item prematurely?
So, with these considerations in mind I went ahead and put together a way of doing what OP had in mind. I extended the example a little bit by including further radio button options:
$.fn.RBuncheckable=function(){ // simple jQuery plugin
const rb=this.filter('input[type=radio]'); // apply only on radio buttons ...
rb.each(function(){this.dataset.flag=$(this).is(':checked')?1:''})
.on('click',function(){
if (this.dataset.flag) $(this).prop('checked',false) // uncheck current
// mark whole group (characterised by same name) as unchecked:
else rb.filter('[name='+this.name+']').each(function(){this.dataset.flag=''});
this.dataset.flag=this.dataset.flag?'':1; // invert flag for current
});
return this;
}
$('input').RBuncheckable(); // apply it to all radio buttons on this page ...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>Two groups of radio buttons with "uncheck" option:</h4>
<input type="text" value="This input field is unaffected">
<p>group one:</p>
<label><input type="radio" name="check" value="a" checked /> Option A</label><br>
<label><input type="radio" name="check" value="b"/> Option B</label><br>
<label><input type="radio" name="check" value="c"/> Option C</label>
<p>group two:</p>
<label><input type="radio" name="second" value="d"/> Option D</label><br>
<label><input type="radio" name="second" value="e"/> Option E</label><br>
<label><input type="radio" name="second" value="f" checked/> Option F</label>
In the .each() loop I collect the initially checked state for all selected radio buttons. I store the individual checked state in a data attribute "flag" for each radio button.
The click event handler function then picks up this data flag and decides whether to step into action by either removing the checked state from the current element or simply resetting the flag data-attributes for the whole group (characterised by having the same name as the currently clicked one). In a last operation it then inverts the flag state for the current element again. As all data attributes are stored as strings, the values 1 and "" are "truthy" and "falsy" values that can be directly tested.
This results in exactly the behaviour you were looking for. I hope ;-)
By having the functionality packaged in a little jQuery plugin it can now be applied to any jQuery object directly.

.remove() function not working as expected jquery

In my project, I have a series of inputs, all of type radio button. I want to add functionality where these inputs can be deleted simply by clicking on the little bubble (the bubble that a radio button is). Here is my code so that I can do this:
$('#newAnswers input').click(function(){
var $textToDelete = $(this).val();
$(this).remove();
});
the reason why I'm assigning the value of the radio button to a textToDelete variable is that usually when you have radio buttons in HTML, you'll have text next to it to describe what that radio button is for. I'm creating a variable to hold this value so that I can delete it from the div manually because the code above works only for removing the radio button, and not the description (or I suppose you could call it the value as well) next to it. The code above also works as expected. HOWEVER, once I implement the functionality to delete the description (or value) next to radio button, the code doesn't work as expected. Here is my implementation:
$('#newAnswers input').click(function(){
var $textToDelete = $(this).val();
$(this).remove();
// NEW LINE
$('#newAnswers').html($('#newAnswers').html().replace($textToDelete, ''));
});
With this click function, after you click a radio button, it deletes, but if you click a second, or a third, or a fourth, or so on, the radio buttons will NOT delete. In fact, clicking on them only fills them in (or bubbles them in) as if you're just selecting a radio button normally. However, the FIRST radio button you click with this function works as expected. However, any radio buttons you click after that will not delete and I don't know why.
HTML Structure:
<div id='newAnswers'>
<input type="radio" value="answer1" name="question">answer1<br>
<input type="radio" value="answer2" name="question">answer2<br>
<input type="radio" value="answer3" name="question">answer3<br>
<input type="radio" value="answer4" name="question">answer4<br>
</div>
you can add span to the text,
<input type="radio" value="answer1" name="question"><span>answer1</span><br>
then
$('#newAnswers input').click(function(){
$(this).next().remove();
$(this).remove();
});
If you want to delete a DOM Element you can use .remove() function. this is the usage of .remove()
$(document).ready(function(){
$('.removebut').click(function(){
$('.removeme').remove();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="removeme">Click to remove me</div>
<button class="removebut">Remove</button>
Or if you want to remove the value of input, you can set value to "" with jquery .val()function.
usage of .val()
$(document).ready(function(){
$('.removebut').click(function(){
$('.removeme').val("");
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="removeme" value="Click To Remove"/>
<button class="removebut">Remove</button>

Why radio button click event behaves differently

Example on JS FIddle.
The question is:
If the first click is on the radio button, it behaves normally; But if the first click is on span text (i.e. aaaa), it can not get the checked radio.
Please tell me why and how I can make it the same.
This code, which happens when the radio button is clicked:
var obj = $(e.target||e.srcElement).parent();
score = obj.find('input:checked').val();
Puts the parent in the obj variable, which is the containing DIV. This contains both of the radio buttons. It then finds the FIRST checked input element in that DIV, which is always the one with the 'first' value after it is checked.
You should just get the value of the item which was clicked:
score = $(e.target||e.srcElement).val();
This can be rewritten as
score = $(this).val();
Here's a working example: http://jsfiddle.net/RPSwD/10/
See new fiddle.
The problem is this line:
score = obj.find('input:checked').val();
Change it to:
score = $(this).val();
The reason for this is that you're looking for the selected item in the div but on the first click, the item has yet to become selected. Given that the event is targeted at the radio button, you can assume that radio is the selected one.
Note also that you don't need to use e.target||e.srcElement. jQuery takes care of this for you. Use $(this) instead.
Additionally, you need to set a name on the radio buttons to stop both from becoming selected. Alternatively, if having both selected is desired behaviour, use check boxes instead.
You don't need to use any of the event properties:
var score = $(this).val(); // in your '.x' click handler
$('.y').click(function(e) {
$(this).prev('.x').click();
});
just wrap your radio button inside label tag like this
<label for="radio1">
<input type=radio class="x" id="radio1" value="First"/>
<span class="y">aaaa</span>
</label>
No need for extra jquery or javascript
check the demo here

How to use jquery to validate whether at least one tick box from #age-groups, #subjects and #topics have been selected

In my upload form I have a few select boxes. These are arranged in divs called #age-groups, #subjects and #topics.
I want to be able to use jquery to make sure the user clicks at least one checkbox from each of the 3 individual divs.
Please could someone help me figure out how to do this.
For when at least one checkbox in each div is clicked I want the function to output:
if (at least 1 checkbox is ticked in each of the 3 divs)
{
$('#two')
.append('<div class="done rotatetwo wiggler"></div>')
.addClass('grey')
}
If possible can this function output the above code as soon as the final required select box is selected.
$(":checkbox").click(function(){
if (($("#age-groups input:checked").length>0) && ($("#subjects input:checked").length>0) && ($("#topics input:checked").length>0){
$('#two').append('<div class="done rotatetwo wiggler"></div>').addClass('grey');
}
});
You need to check the parents of check box/select box for determination.
Have a look at this
basically,
HTML
<fieldset id="age-groups">
<input type="checkbox" name="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>
JavaScript/Jquery
var atLeastOneIsChecked_ageGroups = $('#age-groups :checkbox:checked').length > 0;
will work for you
You'll need to use three selectors to identify any checked checkboxes inside of your three DIVs, then examine the length property of the resulting jQuery objects to make sure that they're greater than zero.
if($('#age-groups input:checkbox:checked').length && ... ) {
// do your stuff here
}
I've only included the selector for the #age-groups div, but you should be able to modify that to select for the other two.
-- misread the question. This would help you if you wanted to check if at least one box is selected across all relevant divs.
try something like this:
if($("#age-groups input[name^='foo']:checked:enabled, #subjects input[name^='foo']:checked:enabled, #topics input[name^='foo']:checked:enabled").length > 0)
// at least one selected
else
// none selected
Of course, this can be simplified if you add a class to all check boxes instead of using the parent div to group them.
if( $("input[name^='foo'].test:checked:enabled").length > 0)
// something selected
Hope this helps!

toggle classes between two radio buttons in jquery

I know this sounds like an easy question but for some reason I just can't figure it out right now. My question is this, let's say I have two radio buttons on my page:
<input type="radio" checked="checked" name=sport value="soccer" />
<input type="radio" name=sport value="basketball" />
What I want to do is that if I click on a radio button, I want to add a class name to it, and if I click on the other radio button, I want to add the same class to that new clicked radio button and I want the class that I added to the previous one removed, and so on....
Any idea please?
Try this.
$("input[name='sport']").click(function(){
$("input[name='sport']").removeClass('className');
$(this).addClass('className');
});
Demo
Well, something like this could do it:
$('input:radio[name="sport"]').click(function() {
$(this).addClass("yourclasshere")
.siblings('input:radio[name="sport"]').removeClass("yourclasshere");
});
Demo: http://jsfiddle.net/yH6ur/
If the radio buttons in your real project are not actually siblings (because they're wrapped in label elements or something) then do it as per Shankar Sangoli's answer.
This is how I did mine to apply to any radio options so I don't have to specify a name each time. I'm sort of new to this so I'm sure someone will have something to say about it. The parent is a label that I have css as a button
$(".noradio").on('click', function(){
var n=$(this).attr("name");
$("input[name='"+n+"']").parent().removeClass('active').removeAttr('checked'); ;
$(this).parent().addClass('active').attr('checked', 'checked');
});
Oh and .noradio is a class on the input itself.

Categories

Resources