Two Checkboxes Being Checked at the Same Time - javascript

I have two checkboxes. What I need is when someone checks one of the boxes, it will automatically check the other one as well. And vice versa, if someone unchecks one of the boxes, it unchecks both. This is a bundle package on the form and they can not get one without the other.
<input type="checkbox" id="chk1" name="chk1" value="100">Voicemail<br />
<input type="checkbox" id="chk2" name="chk2" value="50">VM Support
Any help is greatly appreciated!

Why not this?
<input type="checkbox" id="chk1" name="chk1" value="100">
<label for="chk1">Voicemail and VM Support</label>

Assuming you want to only test these two checkboxes (and not every one on the page), you can use a jQuery Multiple Selector to access the onClick event for both. Using this you can test the checked status of the checkbox that was just clicked, and then assign that status of both checkboxes to match the one that was just clicked.
$('#chk1, #chk2').on('click', function(){
var checked = $(this).is(':checked');
$('#chk1, #chk2').attr('checked', checked);
});

Try this
$('#chk1 , #chk2').on('click', function(){
$('#chk1 , #chk2').attr('checked', $(this).is(':checked'))
});
FIDDLE
FIDDLE

Related

django auto check if i save it to database

Here is my html:
<input type="checkbox" value="1" name="Visual" id="visual">
<input type="checkbox" value="1" name="Tuberculosis" id="Tuberculosis">
<input type="checkbox" value="1" name="Skin" id="Skin">
<script type="text/javascript">
$('#checkbox-value').text($('#checkbox1').val());
$("#checkbox1").on('change', function() {
if ($(this).is(':checked')) {
$(this).attr('value', 'true');
} else {
$(this).attr('value', 'false');
}
$('#checkbox-value').text($('#checkbox1').val());
});
</script>
Here is my view:
Visual = request.POST['Visual']
Tuberculosis = request.POST['Tuberculosis']
Skin = request.POST['Skin']
V_insert_data = StudentUserMedicalRecord(
Visual=Visual,
Tuberculosis=Tuberculosis,
Skin=Skin
)
V_insert_data.save(
Why is it every time I save the data to my database, the Visual, Tuberculosis and Skin are automatically checked even though I didn't check it when I was saving it? Or I think my javascript is wrong?
You don't need $('#checkbox-value').text($('#checkbox1').val());, unless you have such element on the page
which you haven't shown us.
You can't define more than one element on the same page with the same id.
(Same goes for the name attribute).
Use different ids as shown in my code and match the chekboxes by class/name.
Don't put value="1" inside your checkboxes.
Put your jQuery code inside a $(function() { }); which is an alias for $( document ).ready().
More info here.
Don't use bare request.POST values, use the sanitized self.cleaned_data['var_name'] instead.
I don't think it's a good idea to have param names with capital letters (this is just a note, it will not impact the functionality). According
to Python's PEP 8, only classes should start with a capital letter.
Frontend:
<input type="checkbox" name="Visual" id="checkbox1" class="checkbox-js-trigger-class">
<input type="checkbox" name="Tuberculosis" id="checkbox2" class="checkbox-js-trigger-class">
<input type="checkbox" name="Skin" id="checkbox3" class="checkbox-js-trigger-class">
<script type="text/javascript">
$(function() {
$(".checkbox-js-trigger-class").on("change", function(){
var new_val = $(this).is(':checked') ? 1 : 0;
$(this).val(new_val);
});
});
</script>
Backend:
It's best to use Model Form:
class StudentUserMedicalRecordForm(ModelForm):
class Meta:
model = StudentUserMedicalRecord
fields = ['Visual', 'Tuberculosis', 'Skin']
Because you have default value given as "1" here
<input type="checkbox" value="1" name="Visual" id="visual">
And also there is no element with id = "checkbox1" or id = "checkbox-value" which are referenced in your script.
Checkbox inputs are actually a little strange and work differently than how you think they work.
You don't need jQuery to handle the case when a checkbox has been changed. The browser and HTML handle that for you. (Sort of like how you don't need to listen for keys being pressed while the user is focused on a input type="text" to make letters show up in the text box.)
Instead, what happens is if the user checks the checkbox, the input will have an attribute called checked. It can look something like this .
The checkbox input tag also has two other attributes name and value. These are what get sent to the server when the form is submitted. BUT it only sends the name and value pair for the checkboxes that are checked! For the checkboxes that are not checked, it sends nothing. So if every checkbox has a name and value you can think of it as a key-value pair. If the check box is checked, it will send key=value to the server. You are allowed to have more than one value for a single key if you designate the name as being the name of an array.
So imagine you have a form like this:
<input type="checkbox" name="disease[]" value="tuberculosis" checked>
<input type="checkbox" name="disease[]" value="chickenpox" checked>
<input type="checkbox" name="disease[]" value="smallpox">
<input type="checkbox" name="needs_medicine" value="true" checked>
<input type="checkbox" name="recovered" value="whatevervalue">
When that form is submitted, the server will receive something that looks like "disease=[tuberculosis,chickenpox]&needs_medicine=true"
Notice that smallpox and recovered are not mentioned because they are not checked. Also notice that it's not super important what you put as the value of a checkbox that is not a multiple choice checkbox (in this example, needs_medicine) because the value that gets sent to the server will always either be the value of the checkbox (in this case, the string "true").

If I select first checkbox then disable all remaining checkboxes

I have four check boxes inside a separate label.
If I select first check box then all remaining check boxes will be disable. If I click first again, all check boxes will be enabled.
If I select any other check box, the others are still enabled: I can select more than one. See image here
How can I set this up?
Try this:
HTML:
<label for="one"><input type="checkbox" name="one" id="one"></label>
<label for="two"><input type="checkbox" name="two" id="two"></label>
<label for="three"><input type="checkbox" name="three" id="three"></label>
<label for="four"><input type="checkbox" name="four" id="four"></label>
jQuery:
$('input[type="checkbox"]').on('change', function() {
if($('input[type="checkbox"]').eq(0).is(':checked')){
$('input[type="checkbox"]').not($(this)).attr('disabled', true);
}
else{
$('input[type="checkbox"]').not($(this)).attr('disabled', false);
}
});
Working example: https://jsfiddle.net/e26vnnk2/
If you are asking in order to find out how to disable all other "checkboxes," use radiogroups. If you are saying that the first checkbox auto-triggers a toggle on the other checkboxes, try ungrouping them, or making them separate in and of themselves, because it sounds as if you have some kind of faulty grouping and dependency there.

Using check-box in one column to disable check-box in another column

I have a table with two columns of check-boxes, Amend[] and Delete[]. On any row, by checking either one the other is disabled, preventing both being checked. This is my attempt:
var amend=document.getElementByName('Amend');
var del=document.getElementByName('Delete');
function Amend(){
for(x=0;x<amend.length;x++)
{
if(amend[x].checked)
{
del[x].disabled=disabled;
}
}
Any help appreciated.
You want radio buttons, not checkboxes:
<label><input type="radio" name="radio"> Option 1</label>
<label><input type="radio" name="radio"> Option 2</label>
No JavaScript required. Hooray for free functionality!
Got it working. The problem was getElementByName('amend'). It should be getElementsByName('amend[]'), I was referring to one variable called amend instead of an array of elements called amend[].

How change event work on radio buttons

the change function catch only if radio is checked but not when its unchecked. Why? Should it behave like that? When I click the radio button the other is unchanging so the event should fire, right? Below is the code and jsfiddle. Do I do anything wrong?
HTML:
Option1 <input type="radio" name="choice" id="op1" checked/>
Option2 <input type="radio" name="choice" id="op2"/>
<br><br>
<span id="sp1">Option1</span><br>
<span id="sp2" style="display: none;">Option2</span>
Javascript:
var op2 = $('#op2');
var sp1 = $('#sp1');
var sp2 = $('#sp2');
op2.change(function(){
if(op2.is(':checked')){
sp1.hide();
sp2.show();
}
else{
sp2.hide();
sp1.show();
}
});
You can run your event handler when either checkbox changes:
$('#op2, #op1').change(...
Here's a demo: http://jsfiddle.net/TCt82/
Another way to select this would be by element name since both checkboxes need to have the same name attribute. Selecting by ID will be faster (although you won't be able to see the difference).
UPADTE
If anyone knows the exact reason the change event does not fire on a checkbox after it's been de-selected, posting it as a comment or answer would be great.
Change your selector to get it using the name
$("input[name='choice']").change(function(){
if(op2.is(':checked')){
sp1.hide();
sp2.show();
}
else{
sp2.hide();
sp1.show();
}
});
Working sample http://jsbin.com/UPILuCe/1

In jQuery, how do I select an element by its name attribute?

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

Categories

Resources