Radio Button Control in jquery - javascript

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

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

How to select a input with name and value

I need to select a radio input with name and value in jquery
In this example how you select element with name SiblingSex and value female
<form action="">
<input type="radio" name="SiblingSex" value="male">Male<br>
<input type="radio" name="SiblingSex" value="female">Female
<input type="radio" name="ParentSex" value="male">Male<br>
<input type="radio" name="ParentSex" value="female">Female
</form>
i need some thing like
$('input[name="SiblingSex"]' /*GENDER SELECTOR */)
You can add another attribute selector with this:
$('input[name="SiblingSex"][value="female"]').val();
the above line would give you values every time whether it is checked or not.
so if you only want to have the value when it is checked too then add :checked
$('input[name="SiblingSex"][value="female"]:checked').val();
Just have a look on the Demo on my JS Fiddle Code
Shows the two scenario:
1) when you want the value without selecting radio button.
2) when you want value after selecting radio button.
or may be the thing that you want is here::
JS Fiddle Demo

Unchecking a radio box without use of id's

I'm setting up a table, where each row will contain several radio boxes. There are certain conditions for the radio boxes, for example:
If "Home" is checked, the "Text" radio box will be unchecked and "Voice" will be checked instead (ie. You can't text a home phone number). Similarly, when "Home" and "Voice" are checked, clicking "Text" will force "Home" to be unchecked and "Cell" will become checked.
I can get this working fine for one instance, with the use of .getElementById and the click function, but where I run into trouble is when things are scaled up. This table might have 20 or 30 rows, each of which containing a cell with these radio boxes.
I'm not great with jQuery, so I'm not sure how to make a more general version, so that each set of radio boxes are their own contained units, so to speak. I made a jsfiddle where you can see that only the first instance is working, likely because I am targeting the boxes using their id and you can't have two elements with the same id... help? Thanks!
http://jsfiddle.net/3uHqS/
Script
$( document ).ready(function() {
document.getElementById('contact-home').onclick = function () {
document.getElementById('format-voice').checked = true;
};
document.getElementById('format-text').onclick = function () {
document.getElementById('contact-cell').checked = true;
};
});
HTML
<form>
<input type="radio" name="contact" value="" id="contact-cell" />
<label for="contact-cell">Cell</label>
<input type="radio" name="contact" value="" id="contact-home" />
<label for="contact-home">Home</label>
<input type="radio" name="format" value="" id="format-voice" />
<label for="format-voice">Voice</label>
<input type="radio" name="format" value="" id="format-text" />
<label for="format-text">Text</label>
</form>
You are going to want to assign every radio box a descriptive class like 'text-radio' or 'home-radio'. Then when you need to change all of the Text radio boxes you do something like the following in jQuery:
$(".text-radio").attr('checked', 'checked');

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>

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