Web radio buttons where you can switch all off - javascript

I want to have 3 radio type buttons on my web page. If I click on one button it switches on and the other 2 in the group switch off. So far so normal. However if I click the currently 'on' button I want it to toggle to 'off'. I.e. be able to have all buttons in the group switched off.
I've had a look at the jQuery UI button, but I cant figure out how to implement this. Is this possible? Or is there some other javascript library that offers this feature?
Code example of normal jQuery radio buttons ...
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#radio").buttonset();
});
</script>
</head>
<body style="font-size:62.5%;">
<div id="radio">
<input type="radio" id="radio1" name="radio" /><label for="radio1">Choice 1</label>
<input type="radio" id="radio2" name="radio" checked="checked" /><label for="radio2">Choice 2</label>
<input type="radio" id="radio3" name="radio" /><label for="radio3">Choice 3</label>
</div>
</body>
</html>

What you want is, as you know, not how radio buttons work. And it is usually not such a good idea to subvert the usual behavior of any UI element. However, you could have a button labeled, say, "clear all" with an onclick handler that would clear all of the radio buttons. That's a good idea, I think: it's always a pain, imo, to have to select a second radio button to clear the checked state of the first. Of coure, you don't need jquery to do this.
To repeat, though: I wouldn't assign one of the radio-button array to act on others as you describe.

I would have done it this way:
$(window).ready(function() {
var currentRadio = new Array();
$('input:radio').bind('click', function() {
var name = $(this).attr('name');
if(name in currentRadio && currentRadio[name] === $(this)[0]) {
$(this).removeAttr('checked');
currentRadio[name] = false;
} else {
currentRadio[name] = $(this)[0];
}
});
});
This is universal solution for several groups of radio buttons (grouping by name).
Here it is in action: http://jsfiddle.net/LkBYc/

Related

Jquery to Make 2 Sets of Radio Buttons Mirror Eachother

I am trying to setup two sets of radio buttons that will function simultaneously. In other words whenever Male is checked on the top, I would like Male at the bottom to be automatically checked. (and vice versa) If user scrolls down and clicks female then the one at the top should be checked. No matter which radio the user clicks both radio sets should always have the same value checked. Please advise on the most practical way to accomplish this. My main focus is Javascript or Jquery but I have spent several hours trying to come up with something to no avail. Please advise. Thanks! :)
<div class="top">
<input type="radio" name="sex" value="Male" /> Male<br />
<input type="radio" name="sex" value="Female" checked="checked" /> Female<br />
</div>
<div>Random Content</div>
<div class="bottom">
<input type="radio" name="sex2" value="Male" /> Male<br />
<input type="radio" name="sex2" value="Female" checked="checked" /> Female<br />
</div>
Attach to the change event and selecting all other radio buttons which have the same beginning of the name and are of equal value but which are not the current one.
$("input[name^='sex']").change(function(){
var $otherRadioButtons = $("input[name^='sex'][value='" + this.value + "']").not(this);
$otherRadioButtons.prop('checked', $(this).prop('checked'));
});
The above is not using any clever caching of the selectors which you can add yourself.
Basically, whenever a radio button changes it's checked value the code will select all other radio buttons with the same value (male/female) which also start with the same name (sex????) and set their checked property to the same value as the current one.
I hope this makes sense. See a working demo below.
DEMO - Changing radio buttons in a set.
Edit
I just noticed.. I am using jquery 1.3.2 and upgrading isnt an option
at the moment. You don't happen to have a 1.3.2 alternative do you?
For jQuery version 1.3.2 use the attr method instead of the prop method:
$("input[name^='sex']").change(function(){
var $otherRadioButtons = $("input[name^='sex'][value='" + this.value + "']").not(this);
$otherRadioButtons.attr('checked', $(this).attr('checked'));
});
DEMO - Changing radio buttons in a set using jQuery 1.3.2.
Just add an onclick listener to both sets. Like this:
document.getElementById("male1").onclick=clickMale;
document.getElementById("male2").onclick=clickMale;
document.getElementById("female1").onclick=clickFemale;
document.getElementById("female2").onclick=clickFemale;
function clickMale(){
document.getElementById("male1").checked=true;
document.getElementById("male2").checked=true;
}
function clickFemale(){
document.getElementById("female1").checked=true;
document.getElementById("female2").checked=true;
}
And add IDs to the radio buttons ("male1", "male2", "female1", "female2")
Since you mentioned it, Zove's answer in jQuery would be something like this, if you prefer:
$("#male1").click(clickMale);
$("#male2").click(clickMale);
$("#female1").click(clickFemale);
$("#female2").click(clickFemale);
function clickMale(){
$("#male1").attr('checked', true);
$("#male1").attr('checked', true);
}
function clickFemale(){
$("#female1").attr('checked', true);
$("#female2").attr('checked', true);
}
You don't need jQuery for something this simple, but if you're using it elsewhere, it's best to be consistent.
It might make sense, to share a class for both male / female inputs, e.g. 'js-male' or 'js-female'). This saves some code. for instance you could do:
$('.js-male').change(function() {
$('.js-male').attr('checked', $(this).attr('checked'));
});
$('.js-female').change(function() {
$('.js-female').attr('checked', $(this).attr('checked'));
});
There might be more elegant ways to deal with the whole situation so. Do you really want the inputs to have different names ('male', 'male2'), which means that your server receives two different params? If you give both radio button groups the same names, only the value of the last one will be sent to the server, anyway, if you mirror the radio buttons anyway, this doesn't really matter.
Demo
Just change the location of your jQuery source and this will work right out of the box.
<html>
<head>
<script src="jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#male1, #male2").live("click", function(){
$("#male1").attr("checked", $("#male2").attr("checked"));
$("#male2").attr("checked", $("#male1").attr("checked"));
});
$("#female1, #female2").live("click", function(){
$("#female1").attr("checked", $("#female2").attr("checked"));
$("#female2").attr("checked", $("#female1").attr("checked"));
});
});
</script>
</head>
<body>
<div class="top">
<input id="male1" type="radio" name="sex" value="Male" /> Male<br />
<input id="female1" type="radio" name="sex" value="Female" checked="checked" /> Female<br />
</div>
<div>Random Content</div>
<div class="bottom">
<input id="male2" type="radio" name="sex2" value="Male" /> Male<br />
<input id="female2" type="radio" name="sex2" value="Female" checked="checked" /> Female<br />
</div>
</body>
</html>

Radio Button Control in jquery

I'm new to Web development and jQuery.
I'm trying to build an ASPX page with two RadioButton controls that must perform the following actions:
On page load, one of the two must be selected depending on a flag from an object on the ASPX page. Lets call it customer.Id. If the Id is true, select RadioButton one must be set else select RadioButton 2 must be set.
At any point after page load the user selects a RadioButton, the other must be deselected.
When RadioButton two is clicked, hide a Table named "employee table" and when RadioButton one is clicked, show that Table.
Can anyone please tell me how I can get this functionality in jQuery functions?
Not sure about .NET but in Classic ASP you would write a variable like this <%=customerID%>.
In jQuery, I think you can do something like this:
<input type="radio" id="radio1"> Yes
<input type="radio" id="radio2"> No
<table border="1" id="employeeTable">
<tr><td>This is the table</td></tr>
</table>
... and then some jQuery:
$(document).ready(function() {
var customerID = <%=customerID%> // asp variable
if (customerID != "") {
$('#radio1').prop('checked', 'checked');
} else {
$('#radio2').prop('checked', 'checked');
}
$('#radio1').click(function() {
$('#employeeTable').fadeIn('fast');
})
$('#radio2').click(function() {
$('#employeeTable').fadeOut('fast');
})
})
You can have a look/play here: http://jsfiddle.net/qcLtX/7/
Try changing the customerID value to nothing, like var customerID = "".
Good luck
UPDATE
Where I have used .prop: If you are using jQuery version 1.6 or greater, you should use .prop, otherwise, use .attr.
Radio buttons are grouped by their name attribute, like so (source).
<form>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female
</form>
If the radio buttons are grouped, then selecting any one of them automatically delselects all the others in that group.
So the buttons cannot have a distinct name. If you want to distinguish between radio buttons (without referring the their value), you should add an id.
<input type="radio" name="sex" id="m" value="male" />
You can set the selected radio button on page load declaratively in markup, or using jquery.
Declarative version:
<input type="radio" checked="checked" name="sex" value="male" />
jQuery:
$(document).ready(function(){
$("#m").attr("checked", "checked");
});

Button with radio button functionality

I am wondering whether you can make a button, function like a HTML Radio button. I am trying to create a form where the user clicks on the said button and a value is thus selected, but the user is not directed until selecting another option and submitting the form. Does anyone know how to go about doing this?
(I don't mind the use of other languages including javascript etc.)
jQueryUI has a Button Widget that converts radio buttons or checkboxes into buttons.
Example from the site:
http://jqueryui.com/demos/button/#radio
<script>
$(function() {
$( "#radio" ).buttonset();
});
</script>
<div class="demo">
<form>
<div id="radio">
<input type="radio" id="radio1" name="radio" /><label for="radio1">Choice 1</label>
<input type="radio" id="radio2" name="radio" checked="checked" /><label for="radio2">Choice 2</label>
<input type="radio" id="radio3" name="radio" /><label for="radio3">Choice 3</label>
</div>
</form>
</div>
You can visit the link to see it in action.
First, on the page you're talking about, it sounds as if the user is taken somewhere else -- i.e., a submit-like action is taken -- merely by his selecting a radio button. I don't believe that this is the very best practice.
Second, you should imo keep the two radio buttons: they work great and, once selected, a radio button can't be cleared except by selecting another button. This is just what you want.
To be sure that the two buttons you require have been selected, give each button an onclick handler that sets a switch: some button in this group was selected.
Then, when he clicks submit, check those two switches and tell him if he forgot to click a button.
Yes, you need JavaScript to do all this.

Radio buttons + checkbox combinations

The aim is that I have a pair of radio buttons and each pair of radio buttons is inserted in a div with a blog post. I.E. each post can be liked(on)/disliked(off). The checkmark then serves as a universal switch to how all liked/disliked posts. The code below is merely a prototype but I do want to add a second checkbox, enabling users to hide all liked, hide all disliked, hide both (to see which ones haven't been decided on) or none.
In the code below, I cannot get the check box to work independently of the radio buttons. As it is, checking the box switches the radio button to On. I want the radio button to remain where the user wants it and when checking the box, only IF radio is On does the hidden message show. If the radio is Off, checking the box should result in nothing.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-NZ">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Unhide on checkboxes/radio buttons</title>
<script type="text/javascript">
function toggleLayer(val)
{
if(val == 'on' || val === true)
{
document.getElementById('a1').checked = true;
document.getElementById('layer1').style.display = 'block';
}
else if(val == 'off' || val === false)
{
document.getElementById('a2').checked = true;
document.getElementById('layer1').style.display = 'none';
}
}
</script>
</head>
<body>
<form action="" method="post">
<fieldset>
<legend>Unhide Layer Form</legend>
<ul>
<li><label for="a1">On</label> <input id="a1" name="switcher" type="radio" value="off" checked="checked" onclick="toggleLayer(this.checked);" /> <label for="a2">Off</label> <input id="a2" name="switcher" type="radio" value="off" onclick="toggleLayer(!this.checked);" /></li>
<li><label for="b1">Check Me:</label> <input id="b1" name="b1" type="checkbox" value="off" checked="checked" onclick="toggleLayer(this.checked);" /></li>
</ul>
</fieldset>
</form>
<div id="layer1">You can now see this.</div>
</body>
</html>
So, can someone help me modify this code to:
add a second checkbox
Have the first checkbox hide all divs where radio is On
Have the second checkbox hide all divs where radio is Off
Have the radio selections remember where they were so when the user returns, his settings are recalled.
To begin with, you should be aware that the usage of an framework is strongly recommended. eg. take a look at jQuery. example: You can start replacing "document.getElementById" with a $ (char). This lets you focus on the problem solving, instead of how to do it (wich keywords, browser support etc).

Why am I submitting the form twice? jQuery submit() with radio button

I'm using jQuery to submit a form in an MVC app. I have a breakpoint inside the controller and I see it is being hit twice. What am I doing wrong?
Here is my jQuery
(function ($) {
$(document).ready(function () {
$(':radio').change(function () {
$('#frmMDR').submit();
});
});
})(jQuery);
and here is the form html
<form action="/Module/ModuleIndex" id="frmMDR" method="get">
<input id="rdoMaintenance" name="module" type="radio" value="Maintenance" /><label for="rdoMaintenance">M</label>
<input id="rdoDiagnostics" name="module" type="radio" value="Diagnostics" /><label for="rdoDiagnostics">D</label>
<input id="rdoRepair" name="module" type="radio" value="Repair" /><label for="rdoRepair">R</label>
<input id="hdnVehicle" name="hdnVehicle" type="hidden" value="" />
</form>
I'm guessing I shouldn't be using the change event. If anyone knows how to correct the problem, I'd love to hear any ideas. Thanks so much for any tips.
Cheers,
~ck in San Diego
You are getting two hits because two radio buttons are changing state. Radio buttons only allow one element in a group to be selected so when you are clicking a radio button, two events are happening:
A new radio button is selected
The previously selected radio button is deselected
This is two events and the reason why your code is being hit twice. To solve it you could give your radio buttons a class and then handle the event on click using the class as the selector.
<input class="radio" id="rdoMaintenance" name="module" type="radio" value="Maintenance" /><label for="rdoMaintenance">M</label>
<input class="radio" id="rdoDiagnostics" name="module" type="radio" value="Diagnostics" /><label for="rdoDiagnostics">D</label>
<input class="radio" id="rdoRepair" name="module" type="radio" value="Repair" /><label for="rdoRepair">R</label>
And your jQuery could be:
$('.radio').click(function () {
$('#frmMDR').submit();
});
You should probably just check for selected within the change function for which is selected. This way it'll only fire for the selected radio button, and you don't need to worry about binding or unbinding any events, and it should work regardless of what input method changed it.
Here's an article on handling events from check boxes and radio buttons in JQuery.

Categories