Radio buttons uncheck - javascript

EDIT* Answer below fixed the problem if anyone has the same problems.
Small problem with my radio buttons i have three lines each with 3 Radio Buttons, i want the user to be able to check any of the radio buttons on the first two lines but only be able to select one option on each line:
For example
User can only select one option from "keystage1yr1" and can only select one option from "keystage1yr2". This all works fine as they have the same "name" so by defualt the user can only select one for each line.
I have tried:
Deselect Radio Button if another one is selected
How do I deselect a whole group of radio buttons when a user clicks on some other button?
But to know luck although they may help other people.
<input class="radio" type="radio" name="keystage1yr1" value="Paper" /> <span>£25</span>
<input class="radio" type="radio" name="keystage1yr1" value="CD" /> <span>£25 excl VAT</span>
<input class="radio" type="radio" name="keystage1yr1" value="Paper & CD" /> <span>£40 excl VAT</span>
<input class="radio" type="radio" name="keystage1yr2" value="Paper" /> <span>£25</span>
<input class="radio" type="radio" name="keystage1yr2" value="CD" /> <span>£25 excl VAT</span>
<input class="radio" type="radio" name="keystage1yr2" value="Paper & CD" /> <span>£40 excl VAT</span>
<input class="radio" type="radio" name="keystage1save" value="Paper" /> <span>£47.50</span>
<input class="radio" type="radio" name="keystage1save" value="CD" /> <span>£47.50 excl VAT</span>
<input class="radio" type="radio" name="keystage1save" value="Paper & CD" /> <span>£75 excl VAT</span>
Thanks in advance.

Here's some Javascript that should help you out:
// Simply caching the dom queries for speed
$yearstages = $('input[name="keystage1yr2"],input[name="keystage1yr1"]');
$savestages = $('input[name="keystage1save"]');
// I only attach one handler to some parent element:
$('#radios').on('change', 'input', function() {
if (this.name == "keystage1save") {
$yearstages.filter('input:checked').prop('checked', false);
} else {
$savestages.filter('input:checked').prop('checked', false);
}
});
An example of this working: http://jsfiddle.net/CUTnY/

Related

How to toggle a radio button with a label

I would like to unselect a radio button when I click on the label and the following code only works as expected if I click on the button itself.
How to link the behaviour of the label to the button?
<label>
<input type="radio" name="choice" value="HTML" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false" /> Learn HTML
</label>
<label>
<input type="radio" name="choice" value="Java" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false"/> Learn JavaScript
</label>
Radio buttons don't work like you are thinking they do. To deselect one you need to either select another with the same name attribute or reset the form. The functionality that you are describing fits more with a checkbox than a radio button. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio for the specs. You may also want to take a look at this question/answer: Reset Particular Input Element in a HTML Form.
Also, there is no need to wrap your label tag around the input. The for attribute takes care of the linking.
If you want to de-select a radio button, you will need to reset the form.
form {
display: flex;
flex-direction: column;
}
<form>
<label for="ckb-01">
<input id="ckb-01" type="radio" name="choice" value="HTML" />
Learn HTML
</label>
<label for="ckb-02">
<input id="ckb-02" type="radio" name="choice" value="Java" />
Learn JavaScript
</label>
<label for="ckb-03">
<input id="ckb-03" type="radio" name="choice" value="Java" />
Learn CSS
</label>
<input type="reset" />
</form>
use the attribut for in the label
<label for='idHTML'>Learn HTML </label>
give the radio the id equivalent
<input id='idHTML' type="radio" name="choice" />
what do you mean by this.__chk
onMouseDown="this.__chk = this.checked"
onClick="if (this.__chk) this.checked = false"
if you wanna select just one you could use simply type radio with group the options with one name='choice'
if you want check and uncheck multiple choices you could use checkbox
After many attempts I finally managed to code a working solution with some javascript.
The problem is that as soon as the radio button is clicked its state changes. the previous value needs to be stored in order to know if it has to be unselected or not.
<main id="form">
<label >
<input type="radio" name="rad" id="Radio0" />Learn Html
</label>
<br><br>
<label>
<input type="radio" name="rad" id="Radio1" />Learn CSS
</label>
<br><br>
<label>
<input type="radio" name="rad" id="Radio2" />Learn Java
</label>
</main>
<script>
let buttons = document.querySelectorAll('#form input');
for (button of buttons){
button.dataset.waschecked="false";
button.addEventListener('click', myFunction, false);
}
function myFunction(e) {
if (e.originalTarget.dataset.waschecked == "false"){
for (button of document.querySelectorAll('#form input')){
button.dataset.waschecked = "false";
}
e.originalTarget.dataset.waschecked = "true";
e.originalTarget.checked =true;
}else {
for (button of document.querySelectorAll('#form input')){
button.dataset.waschecked = "false";
}
e.originalTarget.checked =false;
}
}
</script>
Any suggestion to improve this code is welcome.

weird bug on radio buttons when change [duplicate]

This question already has answers here:
jquery attr('checked','checked') works only once
(2 answers)
Closed 6 years ago.
i'm trying to do a radio button with 2 options: yes and no (is a long form), but in this piece, i need that radio called refused or accomplished be checked when the user choose yes or no, refused and accomplished buttons already are disabled, the user can't change this manually.
1 - when user choose yes: accomplished must be checked
2 - if user choose no, refused must be checked.
3 - if user change the yes to no, or no to yes option we back to the rules 1 or 2 above.
however, i'm stuck because when i change the option the radio button change only once. and nothing happens after that.
this is my code right now: https://jsfiddle.net/bw21cxo5/1/
HTML:
<div>
<label for="yes">
<input type="radio" name="radio1" value="yes" id="yes" class="option-yes">Yes
</label>
<label for="no">
<input type="radio" name="radio1" value="no" id="no" class="option-no">No
</label>
</div>
<br><br>
<div>
<label for="refused">
<input type="radio" name="radio2" id="refused" disabled> Refused
</label>
<label for="accomplished">
<input type="radio" name="radio2" id="accomplished" disabled> Accomplished
</label>
</div>
js: (jquery 2.2)
$('input[name="radio1"]').on('change', function() {
if ($(this).hasClass('option-no')) {
$('#refused').attr('checked', true);
$('#accomplished').attr('checked', false);
} else {
$('#accomplished').attr('checked', true);
$('#refused').attr('checked', false);
}
});
You can associate the checkboxes with each other. Something like this using the data attribute would work:
Updated HTML
<label for="yes">
<input type="radio" name="radio1" value="yes" id="yes" class="option-yes" data-partner="accomplished">Yes
</label>
<label for="no">
<input type="radio" name="radio1" value="no" id="no" class="option-no" data-partner="refused">No
</label>
JavaScript
$('input[name="radio1"]').on('change', function() {
$('input[name="radio2]').prop('checked',false);
$('#'+$(this).data('partner')).prop('checked',true);
});
JS Fiddle: https://jsfiddle.net/igor_9000/bw21cxo5/3/
Hope that helps!
Your code works enough, only a little fix:
$(function () {
$('input[name="radio1"]').on('change', function() {
if ($(this).hasClass('option-no')) {
$('#refused').prop('checked', true);
} else {
$('#accomplished').prop('checked', true);
}
});
});
<script src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
<div>
<label for="yes">
<input type="radio" name="radio1" value="yes" id="yes" class="option-yes">Yes
</label>
<label for="no">
<input type="radio" name="radio1" value="no" id="no" class="option-no">No
</label>
</div>
<br><br>
<div>
<label for="refused">
<input type="radio" name="radio2" id="refused" disabled> Refused
</label>
<label for="accomplished">
<input type="radio" name="radio2" id="accomplished" disabled> Accomplished
</label>
</div>
It's better to use plain JS when checking radio buttons.
Try this:
$('input[name="radio1"]').on('change', function() {
if ($(this).hasClass('option-no')) {
$('#refused').get(0).checked = true;
} else {
$('#accomplished').get(0).checked = true;
}
});
The problem with your code is instead of attr you should have used prop. Here is the difference between them.
Demo

How to do toggle two mutually exclusive radio buttons in HTML

I have two radio buttons. When I click on one, the other should become unchecked, and vice versa.
The code I've produced so far is not working:
<input type="radio" id="rbdemail" onclick="chekrbdclick()" checked="checked" />
<input type="radio" id="rbdsitelnk" onclick="chekrbdclick()" />
function chekrbdclick()
{
// How to manage here?
}
Simple, just use a 'name' property with the same value for both elements:
<html>
<body>
<form>
<input type="radio" name="size" value="small" checked> Small
<br>
<input type="radio" name="size" value="large"> Large
</form>
</body>
</html>
hope it helps
<form>
<label>
<input type="radio" name="size" value="small" checked> Small
</label>
<br>
<label>
<input type="radio" name="size" value="large"> Large
</label>
</form>
Give them a name attribute with common value like size, and it will work. For best practice, you can place your input tag inside a label tag, so that, even if your user clicks on the text beside the button (ie on "Small" or "Large"), the respective radio button gets selected.
The perfect answer is above answered ,but I wanna share you how it can work by javascript ,this is javascript work (not standard answer) ....
<input type="radio" id="rbdemail" onclick="chekrbdclick(0)" checked="checked" value="Small" />Small<br>
<input type="radio" id="rbdsitelnk" onclick="chekrbdclick(1)" value="Large" />Large
<script>
function chekrbdclick(n)
{
var small = document.getElementById('rbdemail');
var large = document.getElementById('rbdsitelnk');
if(n === 0){
small.checked = true;
large.checked = false;
}
else {
small.checked = false;
large.checked = true;
}
}
</script>

Delete drop down when it is blank using Javascript or Jquery

Is it possible to write a Javascript function to delete a drop down when it is blank?
<form name="myform" method="post" enctype="multipart/form-data" action="" id="myform">
<div>
<label id="question1">1) Draw recognizable shapes</label>
<br />
<input type="radio" value="Yes" id="question1_0" name="question1_0" />
Yes
<input type="radio" value="No" id="question1_1" name="question1_1" />
No
</div>
<div>
<label id="question2">2) Competently cut paper </label>
<br />
<input type="radio" value="Yes" id="question2_0" name="question2_0" />
Yes
<input type="radio" value="No" id="question2_1" name="question2_1" />
No
</div>
<div>
<label id="question3">3) Hold a pencil</label>
<br />
<input type="radio" value="Yes" id="question3_0" name="question3_0" />
Yes
<input type="radio" value="No" id="question3_1" name="question3_1" />
No
</div>
<input type="submit" value="Delete Drop Down" onclick="return checkanddelete"/>
</form>
If somebody does not select question 2 for example, it deletes question 2 label and the drop down.
Assuming you actually meant radio button groups (and not drop down lists) then firstly your HTML is incorrect, you need to set the name values of each group of radio buttons to be the same:
<input type="radio" value="Yes" id="question1_0" name="question1" /> Yes
<input type="radio" value="No" id="question1_1" name="question1" /> No
Then you need to loop through the list of radio buttons, if none in the group are selected then delete the parent div:
$('input[type=submit]').on('click', function() {
var radioArr = [];
$(':radio').each(function(){
var radName = this.name;
if($.inArray(radName, radioArr) < 0 && $(':radio[name='+radName+']:checked').length == 0)
{
radioArr.push(radName);
$(this).closest("div")
.remove();
}
});
return false; //to stop the form submitting for testing purposes
});
While you are there, you might want to add some <label for=""> tags around your text.
Here is a jsFiddle of the solution.
If your dropdown has an id of DropDown, and you are looking to hide the dropdon on submit click:
function checkanddelete()
{
if ( $('#question2_0.=:checked, #question2_1:checked').length )
$('#dropdown').hide() // Or $('#dropdown').remove() if you do not plan on showing it again.
return false; // if you plan on not submitting the form..
}
Optimization for use in a module for a page include adding appropriate ids and classes to the divs, which I'm assuming that in full code are there, but if you are planning on making UI adjustments I would advise against using a submit button in the mix..
I don't know, what do you mean under "dropdown menu", but here some info, that can help you.
You can set a class name for the all Objects, you want to delete. E.g.
HTML
<div>
<label class='question2' id="question2">2) Competently cut paper </label>
<br />
<input class='question2' type="radio" value="Yes" id="question2_0" name="question2_0" />
Yes
<input class='question2' type="radio" value="No" id="question2_1" name="question2_1" />
No
</div>
JS
$(".question2").remove();
As an another solution you can set an ID for the DIV Tag above all of this elements
<div id='block_to_remove'>
<label id="question2">2) Competently cut paper </label>
<br />
<input type="radio" value="Yes" id="question2_0" name="question2_0" />
Yes
<input type="radio" value="No" id="question2_1" name="question2_1" />
No
</div>
And then remove it in JS
$("#block_to_remove").remove();

How can I make a group of checkboxes mutually exclusive?

I have to make mutually exculsive checkboxes. I have come across numerous examples that do it giving example of one checkbox group.
One example is at http://blog.schuager.com/2008/09/mutually-exclusive-checkboxes-with.html.
In my case, I have many checkbox groups on the same page, so I want it to work like this example.
An asp.net codebehind example is here, but I want to do it in client side code.
How can I do this in JavaScript?
i have decided to use the ajax mutually exclusive checkbox extender.
The solutions given so far are basically based on radio buttons.
This link really helped me..http://www.asp.net/ajax/videos/how-do-i-use-the-aspnet-ajax-mutuallyexclusive-checkbox-extender
Using Mutual Checkboxes when there is Radio button is a bad idea but still you can do this as follows
HTML
<div>
Red: <input id="chkRed" name="chkRed" type="checkbox" value="red" class="checkbox">
Blue: <input id="chkBlue" name="chkBlue" type="checkbox" value="blue" class="checkbox">
Green: <input id="chkGreen" name="chkGreen" type="checkbox" value="green" class="checkbox">
</div>
<div>
Mango: <input id="chkRed" name="chkMango" type="checkbox" value="Mango" class="checkbox">
Orange: <input id="chkBlue" name="chkOrange" type="checkbox" value="Orange" class="checkbox">
Banana: <input id="chkGreen" name="chkBanana" type="checkbox" value="Banana" class="checkbox">
</div>
Jquery
$('div .checkbox').click(function () {
checkedState = $(this).attr('checked');
$(this).parent('div').children('.checkbox:checked').each(function () {
$(this).attr('checked', false);
});
$(this).attr('checked', checkedState);
});
And here is fiddle
Like I said in my comment, you should really use <radio> elements for this. Give them the same name and they work almost the same way:
<label><input type="radio" name="option" value="Option 1">Option 1</label>
<label><input type="radio" name="option" value="Option 2">Option 2</label>
The only significant difference is that, once one of them is selected, at least one of them has to be on (ie, you can't uncheck them again).
If you really feel the need to do it with check boxes, remind yourself that users with JavaScript disabled will be able to select all the options if they like. If you still feel the need to do it, then you'll need to give each checkbox group a unique class name. Then, handle the change event of each checkbox element and uncheck all the other elements matching the same class name as the clicked element.
I hope this one will work
HTML
A <input type="checkbox" class="alpha" value="A" /> |
B <input type="checkbox" class="alpha" value="B" /> |
C <input type="checkbox" class="alpha" value="C" />
<br />
1 <input type="checkbox" class="num" value="1" /> |
2 <input type="checkbox" class="num" value="2" /> |
3 <input type="checkbox" class="num" value="3" />
JavaScript
// include jQuery library
var enforeMutualExcludedCheckBox = function(group){
return function() {
var isChecked= $(this).prop("checked");
$(group).prop("checked", false);
$(this).prop("checked", isChecked);
}
};
$(".alpha").click(enforeMutualExcludedCheckBox(".alpha"));
$(".num").click(enforeMutualExcludedCheckBox(".num"));
well, radio button should be the one to be used in mutually excluded options, though I've encountered a scenario where the client preferred to have zero to one selected item, and the javaScript'ed checkbox works well.
Update
Looking at my answer, I realized it's redundant to refer to the css class twice. I updated my code to convert it into a jquery plugin, and created two solutions, depending on ones preference
Get all checkboxes whose check is mutually excluded
$.fn.mutuallyExcludedCheckBoxes = function(){
var $checkboxes = this; // refers to selected checkboxes
$checkboxes.click(function() {
var $this = $(this),
isChecked = $this.prop("checked");
$checkboxes.prop("checked", false);
$this.prop("checked", isChecked);
});
};
// more elegant, just invoke the plugin
$("[name=alpha]").mutuallyExcludedCheckBoxes();
$("[name=num]").mutuallyExcludedCheckBoxes();
HTML
A <input type="checkbox" name="alpha" value="A" /> |
B <input type="checkbox" name="alpha" value="B" /> |
C <input type="checkbox" name="alpha" value="C" />
<br />
1 <input type="checkbox" name="num" value="1" /> |
2 <input type="checkbox" name="num" value="2" /> |
3 <input type="checkbox" name="num" value="3" />
sample code
Group all mutually excluded checkboxes in a containing element
JavaScript
$.fn.mutuallyExcludedCheckBoxes = function(){
var $checkboxes = this.find("input[type=checkbox]");
$checkboxes.click(function() {
var $this = $(this),
isChecked = $this.prop("checked");
$checkboxes.prop("checked", false);
$this.prop("checked", isChecked);
});
};
// select the containing element, then trigger the plugin
// to set all checkboxes in the containing element mutually
// excluded
$(".alpha").mutuallyExcludedCheckBoxes();
$(".num").mutuallyExcludedCheckBoxes();
HTML
<div class="alpha">
A <input type="checkbox" value="A" /> |
B <input type="checkbox" value="B" /> |
C <input type="checkbox" value="C" />
</div>
<div class="num">
1 <input type="checkbox" value="1" /> |
2 <input type="checkbox" value="2" /> |
3 <input type="checkbox" value="3" />
</div>
sample code
Enjoy :-)
Try this:
HTML
<div>
Car: <input id="chkVehicleCar" name="chkVehicle" type="checkbox" value="Car" class="radiocheckbox">
Moto: <input id="chkVehicleMoto" name="chkVehicle" type="checkbox" value="Moto" class="radiocheckbox">
Byke: <input id="chkVehicleByke" name="chkVehicle" type="checkbox" value="Byke" class="radiocheckbox">
Feet: <input id="chkVehicleFeet" name="chkVehicle" type="checkbox" value="Feet">
</div>
<span>
Red: <input id="chkColorRed" name="chkColor" type="checkbox" value="Red" class="radiocheckbox">
Blue: <input id="chkColorBlue" name="chkColor" type="checkbox" value="Blue" class="radiocheckbox">
Green: <input id="chkColorGreen" name="chkColor" type="checkbox" value="Green" class="radiocheckbox">
Mango: <input id="chkFruitMango" name="chkFruit" type="checkbox" value="Mango" class="radiocheckbox">
Orange: <input id="chkFruitOrange" name="chkFruit" type="checkbox" value="Orange" class="radiocheckbox">
Banana: <input id="chkFruitBanana" name="chkFruit" type="checkbox" value="Banana" class="radiocheckbox">
</span>
​JavaScript/jQuery
$(':checkbox.radiocheckbox').click(function() {
this.checked
&& $(this).siblings('input[name="' + this.name + '"]:checked.' + this.className)
.prop('checked', false);
});​
Mutually exclusive checkboxes are grouped by container+name+classname.
You can use different groups in same container and also mix exclusive with non-exclusive checkbox with same name.
JavaScript code is highly optimized. You can see a working example.
No matter where the check box is located on your page, you just need to specify the group and here you go!
<input type='checkbox' data-group='orderState'> pending
<input type='checkbox' data-group='orderState'> solved
<input type='checkbox' data-group='orderState'> timed out
<input type='checkbox' data-group='sex'> male
<input type='checkbox' data-group='sex'> female
<input type='checkbox'> Isolated
<script>
$(document).ready(function () {
$('input[type=checkbox]').click(function () {
var state = $(this)[0].checked,
g = $(this).data('group');
$(this).siblings()
.each(function () {
$(this)[0].checked = g==$(this).data('group')&&state ? false : $(this)[0].checked;
});
});
})</script>
I guess this is what you want.
Consider the HTML below:
<form action="">
My favourite colors are:<br />
<br />
<input type="checkbox" value="red" name="color" /> Red<br />
<input type="checkbox" value="yellow" name="color" /> Yellow<br />
<input type="checkbox" value="blue" name="color" /> Blue<br />
<input type="checkbox" value="orange" name="color1" /> Orange<br />
<input type="checkbox" value="green" name="color1" /> Green<br />
<input type="checkbox" value="purple" name="color1" /> Purple
</form>
Note that there's two names for color groups: red, yellow, blue and orage, green, purple
And this JavaScript noted below will work generically to all checkbox on the page.
jQuery("input[type=checkbox]").unbind("click");
jQuery("input[type=checkbox]").each(function(index, value) {
var checkbox = jQuery(value);
checkbox.bind("click", function () {
var check = checkbox.attr("checked");
jQuery("input[name=" + checkbox.attr('name') + "]").prop("checked", false);
checkbox.attr("checked", check);
});
});
Take a look at this LIVE example

Categories

Resources