Is it possible to solve this situation with JavaScript/jQuery? [duplicate] - javascript

This question already has answers here:
How to allow only one radio button to be checked?
(8 answers)
Closed 3 years ago.
I have a code that checks if radio buttons are checked and if they are it set background color. It's all working fine, my problem is when I want to select another radio button, result is that all my radio buttons are selected on click but it needs to be just one.
$("input[type='radio']").each(function () {
if ($(this).is(":checked")) {
$(this).css("background", "yellow");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio">
<input type="radio" checked>
You can test this out. Just try to select another radio button, you will see that radio buttons are selected (2 radio buttons).
What I want to achieve is that when you click on another radio button it needs to remove this checked class or any other idea. I can't switch between radio buttons.

Give them the same name:
$("input[type='radio']").each(function() {
if ($(this).is(":checked")) {
$(this).css("background", "yellow");
}
});
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<input type="radio" name="radio">
<input type="radio" name="radio" checked>

Radio button can be easily handle with name attribute below code may help you
<input type="radio" name="color">
<input type="radio" name="color" checked>
$("input[name='color']").each(function () {
if ($(this).is(":checked")) {
$(this).css("background", "yellow");
}
});

<input type="radio" name="sameName">
<input type="radio" name="sameName">
set their name like this way

To achieve the desired behavior with visible background color for each radio button, you could wrap each radio <input /> with a span element which would achieve the visual effect of a background color for the radio buttons:
/* Reusable selection of radio buttons */
const radioButtons = $("input[type='radio']");
/* Updates selected radio button parent backgrounds based on checked state */
function updateBackground() {
radioButtons.each(function() {
$(this).parent().css('background', $(this).is(":checked") ? 'yellow' : '');
});
}
/* Attach click behavior to each causing the background colors to update */
radioButtons.click(updateBackground);
/* Initalise the backgrounds and */
updateBackground();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<!-- Wrap each radio button with a span, which will be used to show a colored background
when the radio button is checked -->
<span>
<input type="radio" name="radio-group-name" checked>
</span>
<span>
<input type="radio" name="radio-group-name">
</span>

Related

Add required to input of hidden div when radio is checked

What I'm trying to do is to set hidden div with inputs depended on checked radio input.
This is the logic:
If the first radio is checked the first div is shown, there I want to add hidden inputs with some values...
If the second radio is checked I want the input to be added with required..
And, it shouldn't be required if the 2nd radio isn't checked...
I've tried a few things over some time and got some effects but can't get it work as I want, Here is the code that i'm currently trying to work with, sorry but it's messed up and fails...
So Any help will be much appreciated...
/*
// this code is working but I messed the HTML while trying to get it work with the other code below...
$(document).ready(function() {
$("div.hiddendiv").hide();
check();
$("input[name$='name02']").change(check);
function check() {
var test = $("input[name$='name02']:checked").val();
$("div.hiddendiv").hide();
$("#" + test).show();
}
}
*/
// The code i'm trying to work with...
$(function() {
var radio = $("#closed");
var hidden = $("#hide");
hidden.hide();
checkbox.change(function() {
if (checkbox.is(':checked')) {
hidden.show();
//add required
$('#name02').prop('required', true);
} else {
hidden.hide();
//clear when hidden checked
$("#name02").val("");
//remove required
$('#name02').prop('required', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="closed" value="01"> Closed
<input type="radio" id="open" value="02"> Open
<div name="01" class="hiddendiv">
<input name="name01" type="hidden" value="code">
</div>
<div name="02" id="hide" class="hiddendiv">
<input name="name02" type="text" value="">
</div>
Here is the JSFiddle,
try this code
give same name of radio button so it will work as a group and
also set id of input tag as name02 so its use as a #name02 in jquery
so it will work
$(function() {
var radio = $("#closed");
var hidden = $("#hide");
hidden.hide();
$(this).click(function() {
if ($('#closed').is(':checked')) {
hidden.show();
$('#name02').prop('required', true);
} else {
hidden.hide();
//clear when hidden checked
$("#name02").val("");
//remove required
$('#name02').prop('required', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name='btn' id="closed" value="01"> Closed
<input type="radio" name='btn' id="open" value="02"> Open
<div name="01" class="hiddendiv">
<input name="name01" type="hidden" value="code">
</div>
<div name="02" id="hide" class="hiddendiv">
<input name="name02" id="name02" type="text" value="">
</div>
Part of your problem is that you need to set the name attribute of your radio buttons to be the same value, otherwise the HTML won't know that they belong to the same group.
I've updated the JSfiddle here
https://jsfiddle.net/hba4d83k/2/
What i have done is add a change event handler to your the radio group and then did some conditional logic to show/hide the relevant inputs.

Jquery .val() function to check the value of radio buttons

Below is my logic to check the value of each of the radio buttons. I am using a part of their id's to get hold of the radio buttons. However, my code is always returning a value based on the value of my first radio button. I want it to return the value of each radio button. For example if radio button clicked is yes, then value returned should be 1. Else, 0. Any body who can update my code please.
$('.YesNoRadio').each(function() {
if ($('[id*="YesNo_RadioButtonList_"] input[type="radio"]:checked').val() == 1) {
//$('[id*="AddAttachment"]').trigger('click');
$('[id="upload"]').click();
}
});
Html:
//For yes radio button
<input id="_YesNo_RadioButtonList_0" type="radio" name="YesNo_RadioButtonList" value="1">
//For no
<input id="_YesNo_RadioButtonList_0" type="radio" name="YesNo_RadioButtonList" value="0">
Your selector is incorrect, Remove space from selector. When you use " " it indicates you are targeting child elements i.e. Descendant Selector (“ancestor descendant”)
if($('[id*="YesNo_RadioButtonList_"]:radio:checked').val() == 1)
$('[id="upload"]').click();
And, You don't need .each()
//For yes radio button
<input class="YesNoRadio" id="_YesNo_RadioButtonList_0" type="radio" name="YesNo_RadioButtonList" value="1">
//For no
<input class="YesNoRadio" id="_YesNo_RadioButtonList_0" type="radio" name="YesNo_RadioButtonList" value="0">
<script type="text/javascript">
$('.YesNoRadio').each(function() {
if ($(this).is(':checked')) {
alert($(this).val());
//code for yes radio button
$('[id="upload"]').click();
}else{
alert($(this).val());
//code for no radio button
}
});
</script>
A method that worked for me was setting the name in the html input tag the same for each radio button is your list, which you did:
<input id="_YesNo_RadioButtonList_0" type="radio" name="YesNo_RadioButtonList" value="1">
<input id="_YesNo_RadioButtonList_0" type="radio" name="YesNo_RadioButtonList" value="0">
then I would do this is my JS with JQuery.
var radioButtonValue = $("input[name='YesNo_RadioButtonList']:checked").val();
This should give you the value of your radio button. The value, in your case, is preset in you input tag.
Try this code
$('.YesNoRadio').each(function() {
if ($('[id*="YesNo_RadioButtonList_"] input[type="radio"]:checked').val() == 1) {
//$('[id*="AddAttachment"]').trigger('click');
console.log($(this).val());
$('[id="upload"]').click();
}
});

Jquery clone and appendto for parent element

I have 3 radio buttons which open up the individual divs. All the 3 divs has input boxes which can be added by clicking on the add button next to the input box.
Problem in this now is,
Input boxes should be adding only in the respective radio checked div but now it is aplying for all the 3 div input boxes. If you check on the any one radio button and click on the add button next to input, add few input boxes then go to another radio button and you can see the same action there also which should not actually right.
Here is the code and the fiddle
$filtr = $('.filtr');
$filtr.on('click', '.add', function(){
$(this).closest('.loop').clone().appendTo( $('.test') );
});
$filtr.on('click', '.del', function(){
$(this).closest('.loop').remove();
});
$('#1lev, #2lev, #3lev').hide();
DEMO
have a look here: http://jsfiddle.net/VMBtC/2/
I changed this:
$filtr.on('click', '.add', function(){
$(this).closest('.loop').clone().appendTo( $('.test') );
});
to this:
$filtr.on('click', '.add', function(){
$(this).closest('.loop').clone().appendTo( $(this).closest('.test') );
});
hope it helps
EDIT
radio buttons improvement: check here -> http://jsfiddle.net/VMBtC/3/
JS
$(":radio").click(function(){
$(".test").hide();
var show = $(this).attr("data-show");
$("#"+show).show(300)
});
HTML
<label><input name="1 Level" type="radio" value="0" data-show="1lev" />1 Level</label>
<label><input name="1 Level" type="radio" value="1" data-show="2lev" />2 Level</label>
<label><input name="1 Level" type="radio" value="2" data-show="3lev" />3 Level</label>
Use $(this).closest('.loop').clone().appendTo( $(this).closest('.test') );, otherwise you'd be adding to every .test element.

Disappearing radio button and clickable labels

I want to make radio buttons disappear and instead of buttons, the label of the radio buttons will be clickable itself and i will change the background color of the selected radio. How can i do this? For example, I have "yes" and "no" labels and these labels will be clickable and there will be no radio buttons at all. These are only changing color of background but showing radio buttons which is not wanted.
Javascript
$(document).ready(function(){
var ok = "green";
var notok = "red";
$.each($(":radio"), function(){
if($(this).prop("checked") == false)
{
$(this).parent().css("background", notok);
}
else
{
$(this).parent().css("background", ok );
}
})
$(":radio").click(function(){
$("[name='"+$(this).prop("name")+"']").parent().css("background", notok);
$(this).parent().css("background", ok );
})
})
HTML
<FORM name="form1">
<div>
<input type="radio" id="yes" name="q"checked="checked"/> Yes
</div>
<div>
<input type="radio" id="no" name="q"/>No
</div>
</FORM>
Thanks
This one is actually deceptively easy. If you just use a "label" tag, it will be clickable. Then you can simply hide the radio button.
<input id="yes" type="radio" name="q" value="radiobutton" style="display:none;" />
<label for="yes">Yes </label>
<input id="no" type="radio" name="q" value="radiobutton" style="display:none;" />
<label for="no">No</label>
btw, here's a JSFiddle of it working: http://jsfiddle.net/scGE9/2/
If I understand what you're asking, I'd hide the radio buttons, then attach a click handler to the labels that changed the background color:
$('label').click(function () {
$('label').removeClass('selected');
$(this).addClass('selected');
});
Here's a jsfiddle to demonstrate.
In short, when a label is clicked, remove the 'selected' class controlling the background color from all relevant labels, and apply it to the one that was clicked.

JavaScript: Set background of radio button when deselected (group of radio buttons)

I am trying to create a simple interactive form for use with touch screen devices. The majority of the form is made up of radio buttons in groups of 5 (approx. 37 groups). I have a label tag for each radio button, and when selected (clicked), the background-color property of the label is changed to a highlighted colour using this JavaScript within each label tag OnClick="this.style.background='#5555ff';"
What I want to add to the above, is a JavaScript that will remove the above if the selection is changed within the group. E.g. A user selected radio button A in group 1, then changes their selection to radio button B in group 1. At the moment, both label backgrounds will be changed to the defined colour.
The HTML form is created dynamically by PHP so radio button names, IDs, & values will differ.
I have been unsuccessful trying to complete this task myself, and there doesn't seem to be a simple OnUnClick="xxx" either. I have searched on here for a solution but no questions match mine, although I have tried tweaking existing solutions to similar problems but to no avail.
Thank you for reading!
Here you go:
HTML
<html>
<body>
<div>
<input type="radio" id="g1v1" name="g1" value="v1" checked="checked"/> <label for="g1v1">V1</label>
</div>
<div>
<input type="radio" id="g1v2" name="g1" value="v2" /> <label for="g1v2">V2</label>
</div>
<div>
<input type="radio" id="g1v3" name="g1" value="v3" /> <label for="g1v3">V3</label>
</div>
<div>
<input type="radio" id="g1v4" name="g1" value="v4" /> <label for="g1v4">V4</label>
</div>
</body>
</html>
Javascript
$(document).ready(function(){
var selectedRadioColor = "yellow";
var normalRadioColor = "gray";
// For changing color while document loads
$.each($(":radio"), function(){
//alert( $(this).prop("id")+ $(this).prop("checked") );
if($(this).prop("checked") == false)
{
$(this).parent().css("color", normalRadioColor);
}
else
{
$(this).parent().css("color", selectedRadioColor );
}
})
// For updating color when user interacts with radio buttons
$(":radio").click(function(){
$("[name='"+$(this).prop("name")+"']").parent().css("color", normalRadioColor);
$(this).parent().css("color", selectedRadioColor );
})
})
Here is the link to jsfiddle for live demo:
http://jsfiddle.net/dharmavir/6UnDs/
assuming your radio buttons are grouped in a divs like this -
<div class="radio-group">
<INPUT TYPE=RADIO NAME="pizzasize" VALUE="S">small<BR>
<INPUT TYPE=RADIO NAME="pizzasize" VALUE="M">medium<BR>
<INPUT TYPE=RADIO NAME="pizzasize" VALUE="L">large<P>
</div>
You can do something like this in jquery -
$('input[type="radio"]').click(function(){
var parentElement = $(this).parent();
parentElement.find('input').css('background', '#000000'); //set to your neutral background for radio buttons
$(this).css('background', '5555ff');
});

Categories