Jquery to Make 2 Sets of Radio Buttons Mirror Eachother - javascript

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>

Related

jQuery else clause not working [duplicate]

I have 3 radio buttons in my web page, like below:
<label for="theme-grey">
<input type="radio" id="theme-grey" name="theme" value="grey" />Grey</label>
<label for="theme-pink">
<input type="radio" id="theme-pink" name="theme" value="pink" />Pink</label>
<label for="theme-green">
<input type="radio" id="theme-green" name="theme" value="green" />Green</label>
In jQuery, I want to get the value of the selected radio button when any of these three are clicked. In jQuery we have id (#) and class (.) selectors, but what if I want to find a radio button by its name, as below?
$("<radiobutton name attribute>").click(function(){});
Please tell me how to solve this problem.
This should do it, all of this is in the documentation, which has a very similar example to this:
$("input[type='radio'][name='theme']").click(function() {
var value = $(this).val();
});
I should also note you have multiple identical IDs in that snippet. This is invalid HTML. Use classes to group set of elements, not IDs, as they should be unique.
To determine which radio button is checked, try this:
$('input:radio[name=theme]').click(function() {
var val = $('input:radio[name=theme]:checked').val();
});
The event will be caught for all of the radio buttons in the group and the value of the selected button will be placed in val.
Update: After posting I decided that Paolo's answer above is better, since it uses one less DOM traversal. I am letting this answer stand since it shows how to get the selected element in a way that is cross-browser compatible.
$('input:radio[name=theme]:checked').val();
another way
$('input:radio[name=theme]').filter(":checked").val()
This works great for me. For example you have two radio buttons with the same "name", and you just wanted to get the value of the checked one. You may try this one.
$valueOfTheCheckedRadio = $('[name=radioName]:checked').val();
The following code is used to get the selected radio button value by name
jQuery("input:radio[name=theme]:checked").val();
Thanks
Adnan
For anyone who doesn't want to include a library to do something really simple:
document.querySelector('[name="theme"]:checked').value;
jsfiddle
For a performance overview of the current answers check here
I found this question as I was researching an error after I upgraded from 1.7.2 of jQuery to 1.8.2. I'm adding my answer because there has been a change in jQuery 1.8 and higher that changes how this question is answered now.
With jQuery 1.8 they have deprecated the pseudo-selectors like :radio, :checkbox, :text.
To do the above now just replace the :radio with [type=radio].
So your answer now becomes for all versions of jQuery 1.8 and above:
$("input[type=radio][name=theme]").click(function() {
var value = $(this).val();
});
You can read about the change on the 1.8 readme and the ticket specific for this change as well as a understand why on the :radio selector page under the Additional Information section.
If you'd like to know the value of the default selected radio button before a click event, try this:
alert($("input:radio:checked").val());
You can use filter function if you have more than one radio group on the page, as below
$('input[type=radio]').change(function(){
var value = $(this).filter(':checked' ).val();
alert(value);
});
Here is fiddle url
http://jsfiddle.net/h6ye7/67/
<input type="radio" name="ans3" value="help">
<input type="radio" name="ans3" value="help1">
<input type="radio" name="ans3" value="help2">
<input type="radio" name="ans2" value="test">
<input type="radio" name="ans2" value="test1">
<input type="radio" name="ans2" value="test2">
<script type="text/javascript">
var ans3 = jq("input[name='ans3']:checked").val()
var ans2 = jq("input[name='ans2']:checked").val()
</script>
If you want a true/false value, use this:
$("input:radio[name=theme]").is(":checked")
Something like this maybe?
$("input:radio[name=theme]").click(function() {
...
});
When you click on any radio button, I believe it will end up selected, so this is going to be called for the selected radio button.
I you have more than one group of radio buttons on the same page you can also try this to get the value of radio button:
$("input:radio[type=radio]").click(function() {
var value = $(this).val();
alert(value);
});
Cheers!
can also use a CSS class to define the range of radio buttons and then use the following to determine the value
$('.radio_check:checked').val()
This worked for me..
HTML:
<input type="radio" class="radioClass" name="radioName" value="1" />Test<br/>
<input type="radio" class="radioClass" name="radioName" value="2" />Practice<br/>
<input type="radio" class="radioClass" name="radioName" value="3" />Both<br/>
Jquery:
$(".radioClass").each(function() {
if($(this).is(':checked'))
alert($(this).val());
});
Hope it helps..
$('input:radio[name=theme]').bind(
'click',
function(){
$(this).val();
});
You might notice using class selector to get value of ASP.NET RadioButton controls is always empty and here is the reason.
You create RadioButton control in ASP.NET as below:
<asp:RadioButton runat="server" ID="rbSingle" GroupName="Type" CssClass="radios" Text="Single" />
<asp:RadioButton runat="server" ID="rbDouble" GroupName="Type" CssClass="radios" Text="Double" />
<asp:RadioButton runat="server" ID="rbTriple" GroupName="Type" CssClass="radios" Text="Triple" />
And ASP.NET renders following HTML for your RadioButton
<span class="radios"><input id="Content_rbSingle" type="radio" name="ctl00$Content$Type" value="rbSingle" /><label for="Content_rbSingle">Single</label></span>
<span class="radios"><input id="Content_rbDouble" type="radio" name="ctl00$Content$Type" value="rbDouble" /><label for="Content_rbDouble">Double</label></span>
<span class="radios"><input id="Content_rbTriple" type="radio" name="ctl00$Content$Type" value="rbTriple" /><label for="Content_rbTriple">Triple</label></span>
For ASP.NET we don't want to use RadioButton control name or id because they can change for any reason out of user's hand (change in container name, form name, usercontrol name, ...) as you can see in code above.
The only remaining feasible way to get the value of the RadioButton using jQuery is using css class as mentioned in this answer to a totally unrelated question as following
$('span.radios input:radio').click(function() {
var value = $(this).val();
});

jQuery autoselect radiobox is not working

I cannot get my jquery code to auto select a radiobox.
Here is my html:
<div class="formField rsform-block rsform-block-existingcustomer" style="margin-bottom: -22px;">
<!--<input name="form[existingCustomer]" type="radio" value="Yes" id="existingCustomer0" /><label for="existingCustomer0">Yes</label><input checked="checked" name="form[existingCustomer]" type="radio" value="No" id="existingCustomer1" /><label for="existingCustomer1">No</label><br/>
<span id="component100" class="formNoError">Please tell us if you're an existing customer.</span>-->
Are you an existing client?<br>
<label for="existingCustomer0" class="radio"><span class="icon"></span><span class="icon-to-fade"></span>Yes
<input name="form[existingCustomer]" type="radio" value="Yes" id="existingCustomer0" class="addRadio">
</label>
<label for="existingCustomer1" class="radio checked"><span class="icon"></span><span class="icon-to-fade"></span>No
<input checked="checked" name="form[existingCustomer]" type="radio" value="No" id="existingCustomer1" class="addRadio" style="display:none;">
</label>
</div>
and here is a snippet of the jQuery code that is supposed to do it:
if(aaid) {
var num_one = aaid;
jQuery('input[value="Yes"]').prop('checked', true);
Does anyone see the problem? I am trying to autoselect the "yes" checkbox, so that it will activate the next part which is create a dropdown menu.
Thanks in advance! :)
Try this:
$(document).ready(function () {
$('input:radio[name="form[existingCustomer]"][value="Yes"]').attr('checked',true);
//OR
$('input:radio[name="form[existingCustomer]"][value="Yes"]').prop('checked',true);
});
Example
I see a couple issues with your code here.
1. input hmtl does not have proper ending/end tag
2. not sure why you wrap it around the label
3. Be sure to put your jquery code in document ready so that it checks the radiobox when the page is loaded.
4. in you html code, you are pre-setting the No radio to be checked. Is that on purpose? It looks like you set it to no and then using jquery to set it back to yes.
Anyway, try attr instead of prop. Something like this.
$('input:radio[value="Yes"]').attr('checked', true);

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");
});

Web radio buttons where you can switch all off

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/

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.

Categories