using checkbox as radio button - javascript

I am looking for a way for users to select one of the two options (strength or weakness) for a list of qualities.
for eg:
strength weakness not applicable
1. Communication
2. Punctuality
...
Radio button lets me select either a strength or weakness. However, I want the user to check only those qualities that apply and if a user accidentally selects a quality there is no way to undo the selection for a radio button unless there is a third radio button called not applicable or have the user re-enter the page. I was wondering if there is a way to be able to get the flexibility of a checkbox (check / uncheck) in addition to disabling or enabling the other checkbox when one of them is checked or unchecked instead of using three radio buttons.
I don't think I have seen this behavior before so wondering if there is a more elegant way of doing this. I am open to other ideas to get the same functionality. Using a checkbox as radio button was just a thought.
thanks much.

Solution based on javascript
function SetSel(elem)
{
var elems = document.getElementsByTagName("input");
var currentState = elem.checked;
var elemsLength = elems.length;
for(i=0; i<elemsLength; i++)
{
if(elems[i].type === "checkbox")
{
elems[i].checked = false;
}
}
elem.checked = currentState;
}​
<input type="checkbox" class="chkclass" onclick="SetSel(this);" />
<input type="checkbox" class="chkclass" onclick="SetSel(this);" />
<input type="checkbox" class="chkclass" onclick="SetSel(this);" />
<input type="checkbox" class="chkclass" onclick="SetSel(this);" />
Working Demo
Solution based on jQuery
$(function(){
$("input:checkbox.chkclass").click(function(){
$("input:checkbox.chkclass").not($(this)).removeAttr("checked");
$(this).attr("checked", $(this).attr("checked"));
});
});​
<input type="checkbox" class="chkclass" />
<input type="checkbox" class="chkclass" />
<input type="checkbox" class="chkclass" />
<input type="checkbox" class="chkclass" />
Working Demo

You should not use checkboxes as radio buttons (or vice-versa): this is inconsistent with the user's mental model, so it confuses people.
This is a problem with no ideal solution, but your initial suggestion of having a "not applicable" option as part of a group of 3 radio buttons is fairly common. If you pre-select the "not applicable" option by default and perhaps de-emphasize it visually (eg. gray it out) then from the user's point of view it will be almost as if there are only 2 options, but they can recover if they accidentally select one and want to "unselect" it.

this is correct form, "checked" is a proprietary and not attribute
$(function(){
$("input:checkbox.chkclass").each(function(){
$(this).change(function(){
$("input:checkbox.chkclass").not($(this)).prop("checked",false);
$(this).prop("checked", $(this).prop("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 disable a textbox if particular radio button is clicked using jquery?

I have a html form in which I have four radio buttons and one text box. What I am trying to do is - Once I click Test4 radio button, I want to disable node textbox so that nobody can type anything in that. I don't want to hide it, I just want to disable it.
But if anybody clicks either Test1 or Test2 or Test3 then anybody can type anything into it.
Here is my jsfiddle
Is this possible to do using jquery?
Yes, this is possible; I'd suggest:
$('input[type="radio"]').change(function(){
$('#node').prop('disabled', this.value === 'test4');
});
JS Fiddle demo.
This sets the disabled property of the #node element to true (if the changed-element has the value of 'test4'), and to false if it does not.
Further to the discussion in comments (wherein, basically, the OP revealed that checking other input elements of type="radio" caused the #node element to become re-enabled), I've amended the HTML to offer a simple means of associating the appropriate inputs with the specific text-input, using data-affects. giving the following HTML:
<input type="radio" name="data" id="test1" value="test1" data-affects="nodes" />Test1
<input type="radio" name="data" id="test2" value="test2" data-affects="nodes" />Test2
<input type="radio" name="data" id="test3" value="test3" data-affects="nodes" />Test3
<input type="radio" name="data" id="test4" value="test4" data-affects="nodes" />Test4
Coupled with the amended jQuery:
$('input[type="radio"][data-affects]').change(function(){
$('#' + this.getAttribute('data-affects')).prop('disabled', this.value === 'test4');
});
JS Fiddle demo.
References:
change().
prop().
To your jsfiddle, add on the top of js this piece of code:
$("input:radio[name=data]").change(function () {
var checkedValue = $(this).val();
if (checkedValue == "test4") {
$("#node").prop("disabled", true);
} else {
$("#node").prop("disabled", false);
}
});
You can also call the radio group by id instead of name:
$("input:radio[id=data]").change(function () { //first line of code
Live example here: http://jsfiddle.net/pw9nZ/
Hope this helps you...
Theo.

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');

How to detect if a one radio button in a group has been selected with jQuery

I'm 95% there in writing an HTML5 'required' attribute fallback, I'm having a small issue and I've come to the end of the road in my knowledge!
What works:
Detecting 'required' attributes, looping through and alerting the user in several ways (onsubmit and entering data into the field).
Problem:
I'm taking the form one step further and want to make checkboxes and radio buttons required as well. By doing this, I need to add a required attribute to each radio/checkbox. I need to find out how to differentiate the group of buttons, as currently you need to tick/untick both sets of buttons for the form to validate and let you submit. So in a nutshell, I have three required radios for example, each will need to be ticked, how can I detect whilst looping through the inputs that one of the required radios/checked is ticked - I assume this would be done by matching the 'name' attribute, and if none in the name group are selected then alert just one error.
Here's the state of my loop, you can see I detect the input type as well, just unsure of the next steps forward. a jsFiddle is also below if anyone would be kind enough to help out. Many thanks.
// loop through class name required
$('.required').each(function () {
// this
var self = $(this)
// check shorthand if statement for input[type] detection
var checked = (self.is(':checkbox') || self.is(':radio')) ? self.is(':not(:checked)') : false
// run the empty/not:checked test
if (self.val() === '' || checked) {
// show error if the values are empty still (or re-emptied)
// this will fire after it's already been checked once
self.siblings('.form-error').show()
// stop form submitting
e.preventDefault()
// if it's passed the check
} else {
// hide the error
self.siblings('.form-error').hide()
}
})
Here's my jsFiddle: http://jsfiddle.net/zykF9/
With class selectors you could archive it
http://jsbin.com/owokuw/1/edit
UPDATE
to make easier to understand, here a update:
<input type="radio" name="myradio" class="myradio" />
<input type="radio" name="myradio" class="myradio" />
<input type="radio" name="myradio" class="myradio" />
<input type="radio" name="myradio" class="myradio" />
<input type="hidden" id="selectedRadioYes" />
<input type="button" id="botton" value="Botton" />
Jquery
$(".myradio").click(function(){
$("#selectedRadioYes").val(1);
});
$("#botton").click(function(){
if($("#selectedRadioYes").val() === "1")
alert("you can go on");
else
alert("need select one radio");
});
http://jsbin.com/owokuw/2/edit

Checkbox Validations

I cant simply get my head around javascript validations. I've seen tutorials and its just not getting to me. Someone please give me a SIMPLE step by step guide on how I can add validations to checkboxes. So say this is my form:
<form name="form1" method = "post">
<input name="Conservatives" type="checkbox" value="Conservatives" /> Conservative
<input name="Liberal Democrats" type="checkbox" value="Liberal Democrats" /> Liberal Democrats
<input name="Labour" type="checkbox" value="Labour" /> Labour
</form>
i want the user to select at least 2 checkboxes. the validation should be done from the client side of things which i will then take the values using php to send to the database?
any help guys?
It looks like you actually want radio buttons, not checkboxes.
If that is the case, use this:
<form action="" method="post">
<label><input type="radio" name="vote" value="Conserv" /> Conservative</label><br />
<label><input type="radio" name="vote" value="LibDem" /> Liberal Democrats</label><br />
<label><input type="radio" name="vote" value="Labour" /> Labour</label><br />
</form>
Then, in whatever server-side code you have, the vote POST variable will have either "Conserv", "LibDem" or "Labour" depending on user choice.
So you want to validate that, based on your comment, at least two of these checkboxes are checked? I would give them all the same name:
<input name="partyAffiliation" type="checkbox" value="Conservatives" /> Conservative
<input name="partyAffiliation" type="checkbox" value="Liberal Democrats" /> Liberal Democrats
<input name="partyAffiliation" type="checkbox" value="Labour" /> Labour
Then loop them and see how many are checked. document.getElementsByName will give you the checkboxes, each of which will have a checked property.
var allCbs = document.getElementsByName("partyAffiliation");
var numChecked = 0;
for(var i = 0, max = allCbs.length; i < max; i++)
if (allCbs[i].checked)
numChecked++;
if (numChecked < 2)
alert("Select at least two parties!");
I don't know the details of your project, but I'll just mention that jQuery will make the above code quite simple, if using this library is something you're not opposed to:
var numChecked = $("input[name='partyAffiliation']:checked").length;
if (numChecked < 2)
alert("Select at least two parties!");
EDIT
In response to a comment below, don't worry about having multiple inputs with the same name. Your server-side code should receive a comma delimited list of all (selected) values associated with that name. So if you check all three checkboxes, you'd see something like the below.

Categories