Click checkbox based on label name - javascript

I have two checkboxes with labels named Headline A and Headline B. I'm trying to come up with a way to activate the checkbox of Headline B if the checkbox of Headline A is checked - and vice versa.
<input type="checkbox">
<label>HEADLINE A</label>
<input type="checkbox">
<label>HEADLINE B</label>
This is what I started on, but I'm afraid it's not even close.
if($("label:contains('HEADLINE A')").closest('input').is(':checked')){
$("label:contains('HEADLINE B')").closest('input').is(':checked')
}
Do I use regex to match the word 'headline' and then come up with the appropriate action?

closest selects the closest parent of an element not the closest sibling, if you want to modify the checked property of an input you should use prop method instead of is.
if ( $("label:contains('HEADLINE A')").prev('input').is(':checked') ) {
$("label:contains('HEADLINE B')").prev('input').prop('checked', true)
}
Or:
var state = $("label:contains('HEADLINE A')").prev('input').is(':checked');
$("label:contains('HEADLINE B')").prev('input').prop('checked', state);
In case that you want to modify the checked property based on change event you can try:
$('input[type=checkbox]').filter(function() {
return $(this).next().text() === 'HEADLINE A'
}).change(function() {
$("label:contains('HEADLINE B')").prev('input').prop('checked', this.checked)
})
http://jsfiddle.net/FvLyJ/

I believe that the application must set the input of html with marked or not, right? Following this premise, I believe the solution is this:
var headlineA = $("label:contains('HEADLINE A')").prev('input');
var headlineB = $("label:contains('HEADLINE B')").prev('input');
headlineA.attr('disabled', true);
headlineB.attr('disabled', true);
if(headlineA.is(':checked')){
headlineB.attr('disabled', false);
}
if(headlineB.is(':checked')){
headlineA.attr('disabled', false);
}
You see here. Just set one of the inputs as html checked.

If these are the only two Checkboxes then you can use something like this
$('input[type="checkbox"]').on('click', function() {
var $this = $(this);
if( $this.is(':checked')){
$('input[type="checkbox"]').not($this).prop('checked' , true);
}
});​
Fiddle
If check/uncheck
$('input[type="checkbox"]').on('click', function() {
var $this = $(this);
$('input[type="checkbox"]').not($this).prop('checked' , this.checked);
});​

Related

Making two exclusive checkbox inside div

I have followed this JS Fiddle from this question.
Here's my HTML code:
<div id="paramStart">
<div id="gameType">
<div id="UserVsComputer" class="checkbox" style="margin-left: 8px;">
<label><input type="checkbox" value="">User vs Computer</label>
</div>
<br>
<br>
<div id="User1VsUser2" class="checkbox" style="margin-left: 8px;">
<label><input type="checkbox" value="">User1 vs User2</label>
</div>
</div>
I did in JavaScript:
var gameType = document.getElementById('gameType');
gameType.addEventListener('click', setGameType, false);
function setGameType() {
var checkInput = $('#gameType .checkbox > label > input');
console.log(checkInput);
checkedState = checkInput.attr('checked');
checkInput.attr('checked').each(function () {
$(this).attr('checked', false);
});
checkInput.attr('checked', checkedState);
}
But I get the following error:
TypeError: checkInput.attr(...) is undefined
I try to access the <input> tag for setting true to the clicked <input>
Where is my error?
Update
#Mohamed-Yousef
To get the array of checked inputs, I did:
var checkInput = $('#gameType > div > input[type="checkbox"]');
console.log(checkInput.attr());
I get:
TypeError: a is undefined jquery-latest.min.js:4:9978
This entire thing can be simply:
NOT capturing the current state:
$('#gameType').on('click','.checkbox',function(){
$(this).siblings().find('input[type="checkbox"]')[0].checked = false;
});
OR
$('#gameType').on('click','.checkbox',function(){
$(this).siblings().find('input[type="checkbox"]').prop('checked', false);
});
Un-check the other box no matter what the current checkbox state is:
$('#gameType').on('click','.checkbox',function(){
var checkBoxState = $(this).find('input[type="checkbox"]')[0].checked;
$(this).siblings().find('input[type="checkbox"]')[0].checked = false;
});
OR
Make the OTHER checkbox the opposite of this one:(NOTE: both cannot be "unchecked" using this.)
$('#gameType').on('click','.checkbox',function(){
var checkBoxState = $(this).find('input[type="checkbox"]')[0].checked;
console.log(checkBoxState);
$(this).siblings().find('input[type="checkbox"]')[0].checked = !checkBoxState;
});
EDIT: Note that this way, you can click the label as well as the checkbox which might enhance the user experience but you would need to decide that.
IF the syntax above is not desired you can also manage the property with jQuery as:
$(this).siblings().find('input[type="checkbox"]').prop("checked", false);
OR
EDIT: Here, we then use the .prop() to both get and set:
$('#gameType').on('click','.checkbox',function(){
var checkBoxState = $(this).find('input[type="checkbox"]').prop("checked");
console.log(checkBoxState);
$(this).siblings().find('input[type="checkbox"]').prop("checked", checkBoxState);
});
EDIT: here is another method using .is()
$('#gameType').on('click','.checkbox',function(){
var checkBoxState = $(this).find('input[type="checkbox"]').is(":checked");
console.log(checkBoxState);
$(this).siblings().find('input[type="checkbox"]').prop("checked", checkBoxState);
});
up to your html structure you can change the game type when user checked the checkbox and unchecked another one
var gameType = $('input[type="checkbox"]');
gameType.on('click', function(){
setGameType($(this));
});
function setGameType(el) {
if(el.is(':checked')){
$('input[type="checkbox"]').not(el).prop('checked' , false);
}
}
Working Demo
and about your code
$('#gameType .checkbox > label > input').attr();
Its an array of inputs not just one input to get attr for.. You can use it inside .each to get attr for each checkbox by using
checkInput.each(function () {
alert( $(this).attr('checked'));
});

How to check 2 checkboxes that have the same name

So I have a ajax search form which gives results with a checkbox:
Here is part of PHP code for each search result:
<input type="checkbox" class="lovkrav_checkbox checkbox_search" name="lovkrav['.$lovkrav_id.']" value="'.$lovkrav_id.'" orig-id="lovkrav'.$lovkrav_id.'" id="lovkravs'.$lovkrav_id.'" '.$checked.'/>
and there is a twin checkbox already on website with the same name but with different id.
By using "orig-id" property I am getting the id of the twin checkbox. Both checkboxes have same class lovkrav_checkbox.
I came to the point where the click event is detected by the twin checkbox as it should but not the checkbox you clicked on!
Here is the code:
$(document).on("click",".lovkrav_checkbox",function(e){
toggle_id = document.getElementById($(this).attr("orig-id"));
$(toggle_id).trigger("click");
});
What I want to achieve is when a user clicks on one checkbox - the twin checkbox (the one with same name property) will be checked/unchecked as well.
What am I doing wrong?
Would be easier to toggle the checked state with vanilla javascript.
HTML
<input type="checkbox" name="test">
<input type="checkbox" name="test">
JS
//All of the checkboxes
var $checkboxes = $("input[type=checkbox][name=test]");
//The event handler
$checkboxes.on("click", function() {
//Get the state of the check box you clicked
var checkedState = this.checked
//Make it the state of all the checkboxes
$checkboxes.each(function() {
this.checked = checkedState;
});
});
Here is the fiddle
You can try this:
DEMO
$(document).on("click",".check",function(e){
$("."+this.className).prop("checked", this.checked);
});
Try this too:
js:
$(document).on("click",".lovkrav_checkbox",function(e){
toggle_id = $(this).attr("name");
isChecked = $(this).prop("checked");
$("input:checkbox").each(
function(){
if($(this).attr("name") == toggle_id && isChecked){
$(this).prop("checked",true);
}
else{
$(this).prop("checked",false);
}
});
});
fiddle
Try this
$("input[type=checkbox][name=test]").prop("checked",true);

How to select other checkbox when the last value is checked

Here an example of my checkbox list http://jsfiddle.net/YnM2f/
Let's say I check on G then A,B,C,D,E,F also automatic checked. How can i achieve my goals with jQuery?
First you need to get all the checkboxes based on which one is clicked. for this you need to get the parent nodes, siblings that are before it. Here is some code that will help you get there, but you'll need to work on it to make it work for you.
http://jsfiddle.net/urau8/
$("input:checkbox").on("click",function(){
if(this.checked)
$(this).parent().prevAll().each(function(){
$("input:checkbox",this).attr("checked",true);
});
});
This will check all checkboxes above a checkboxe that gets checked and uncheck all checkboxes above a checkbox that gets unchecked, given the checkbox layout that you've provided.
$('input:checkbox').click(function () {
var state = $(this).prop('checked');
var elements;
if (state) {
elements = $(this).parent().prevAll();
} else {
elements = $(this).parent().nextAll();
}
elements.each(function () {
$('input:checkbox', this).prop('checked',state);
});
});
$('input:checkbox').change(function(){
var $allParents = $(this).parent();
$allParents.prevAll().find('input').attr('checked', 'checked');
$allParents.nextAll().find('input').removeAttr('checked');
});
Try this
Well it's already been done five times, but this is what I did: http://jsfiddle.net/YnM2f/27/
$('input').click(function(){
if( $(this).is(':checked') ){
$(this).parent('p').prevAll().children('input').attr('checked',true)
}
})
Try something like this: http://jsfiddle.net/YnM2f/16/
It's a very specific solution (as in it will only work with "G"), but it should give you an idea for how to customize this code to meet your needs.
$('input:checkbox').filter(function(){
return (/ G/).test($(this).parent().text())
}).on('change', function() {
var gBox = $(this);
$('input:checkbox').prop('checked', $(gBox).prop('checked'));
});

Check/Uncheck checkbox with JavaScript

How can a checkbox be checked/unchecked using JavaScript?
Javascript:
// Check
document.getElementById("checkbox").checked = true;
// Uncheck
document.getElementById("checkbox").checked = false;
jQuery (1.6+):
// Check
$("#checkbox").prop("checked", true);
// Uncheck
$("#checkbox").prop("checked", false);
jQuery (1.5-):
// Check
$("#checkbox").attr("checked", true);
// Uncheck
$("#checkbox").attr("checked", false);
Important behaviour that has not yet been mentioned:
Programmatically setting the checked attribute, does not fire the change event of the checkbox.
See for yourself in this fiddle:
http://jsfiddle.net/fjaeger/L9z9t04p/4/
(Fiddle tested in Chrome 46, Firefox 41 and IE 11)
The click() method
Some day you might find yourself writing code, which relies on the event being fired. To make sure the event fires, call the click() method of the checkbox element, like this:
document.getElementById('checkbox').click();
However, this toggles the checked status of the checkbox, instead of specifically setting it to true or false. Remember that the change event should only fire, when the checked attribute actually changes.
It also applies to the jQuery way: setting the attribute using prop or attr, does not fire the change event.
Setting checked to a specific value
You could test the checked attribute, before calling the click() method. Example:
function toggle(checked) {
var elm = document.getElementById('checkbox');
if (checked != elm.checked) {
elm.click();
}
}
Read more about the click method here:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
to check:
document.getElementById("id-of-checkbox").checked = true;
to uncheck:
document.getElementById("id-of-checkbox").checked = false;
We can checked a particulate checkbox as,
$('id of the checkbox')[0].checked = true
and uncheck by ,
$('id of the checkbox')[0].checked = false
Try This:
//Check
document.getElementById('checkbox').setAttribute('checked', 'checked');
//UnCheck
document.getElementById('chk').removeAttribute('checked');
I would like to note, that setting the 'checked' attribute to a non-empty string leads to a checked box.
So if you set the 'checked' attribute to "false", the checkbox will be checked. I had to set the value to the empty string, null or the boolean value false in order to make sure the checkbox was not checked.
Using vanilla js:
//for one element:
document.querySelector('.myCheckBox').checked = true //will select the first matched element
document.querySelector('.myCheckBox').checked = false//will unselect the first matched element
//for multiple elements:
for (const checkbox of document.querySelectorAll('.myCheckBox')) {
//iterating over all matched elements
checkbox.checked = true //for selection
checkbox.checked = false //for unselection
}
function setCheckboxValue(checkbox,value) {
if (checkbox.checked!=value)
checkbox.click();
}
<script type="text/javascript">
$(document).ready(function () {
$('.selecctall').click(function (event) {
if (this.checked) {
$('.checkbox1').each(function () {
this.checked = true;
});
} else {
$('.checkbox1').each(function () {
this.checked = false;
});
}
});
});
</script>
For single check try
myCheckBox.checked=1
<input type="checkbox" id="myCheckBox"> Call to her
for multi try
document.querySelectorAll('.imChecked').forEach(c=> c.checked=1)
Buy wine: <input type="checkbox" class="imChecked"><br>
Play smooth-jazz music: <input type="checkbox"><br>
Shave: <input type="checkbox" class="imChecked"><br>
If, for some reason, you don't want to (or can't) run a .click() on the checkbox element, you can simply change its value directly via its .checked property (an IDL attribute of <input type="checkbox">).
Note that doing so does not fire the normally related event (change) so you'll need to manually fire it to have a complete solution that works with any related event handlers.
Here's a functional example in raw javascript (ES6):
class ButtonCheck {
constructor() {
let ourCheckBox = null;
this.ourCheckBox = document.querySelector('#checkboxID');
let checkBoxButton = null;
this.checkBoxButton = document.querySelector('#checkboxID+button[aria-label="checkboxID"]');
let checkEvent = new Event('change');
this.checkBoxButton.addEventListener('click', function() {
let checkBox = this.ourCheckBox;
//toggle the checkbox: invert its state!
checkBox.checked = !checkBox.checked;
//let other things know the checkbox changed
checkBox.dispatchEvent(checkEvent);
}.bind(this), true);
this.eventHandler = function(e) {
document.querySelector('.checkboxfeedback').insertAdjacentHTML('beforeend', '<br />Event occurred on checkbox! Type: ' + e.type + ' checkbox state now: ' + this.ourCheckBox.checked);
}
//demonstration: we will see change events regardless of whether the checkbox is clicked or the button
this.ourCheckBox.addEventListener('change', function(e) {
this.eventHandler(e);
}.bind(this), true);
//demonstration: if we bind a click handler only to the checkbox, we only see clicks from the checkbox
this.ourCheckBox.addEventListener('click', function(e) {
this.eventHandler(e);
}.bind(this), true);
}
}
var init = function() {
const checkIt = new ButtonCheck();
}
if (document.readyState != 'loading') {
init;
} else {
document.addEventListener('DOMContentLoaded', init);
}
<input type="checkbox" id="checkboxID" />
<button aria-label="checkboxID">Change the checkbox!</button>
<div class="checkboxfeedback">No changes yet!</div>
If you run this and click on both the checkbox and the button you should get a sense of how this works.
Note that I used document.querySelector for brevity/simplicity, but this could easily be built out to either have a given ID passed to the constructor, or it could apply to all buttons that act as aria-labels for a checkbox (note that I didn't bother setting an id on the button and giving the checkbox an aria-labelledby, which should be done if using this method) or any number of other ways to expand this. The last two addEventListeners are just to demo how it works.
I agree with the current answers, but in my case it does not work, I hope this code help someone in the future:
// check
$('#checkbox_id').click()

jQuery: Problems with detecting if a checkbox is checked

I'm creating a small jQuery plugin for my CMS that styles certain form input types (just radio, checkbox at the moment). It works by hiding the original form element and placing a normal HTML element (for styling with CSS) in the input's place. It then detects actions on the element and updates the original input accordingly. Additionally, it will also work when the associated label is clicked. Here is my code:
jQuery.fn.ioForm = function() {
return this.each(function(){
//For each input element within the selector.
$('input', this).each(function() {
var type = $(this).attr('type');
//BOF: Radios and checkboxes.
if (type == 'radio' || type == 'checkbox') {
var id = $(this).attr('id');
checked = '';
if ($(this).attr('checked')) {
checked = 'checked';
}
//Add the pretty element and hide the original.
$(this).before('<span id="pretty_'+ id +'" class="'+ type +' '+ checked +'"></span>');
$(this).css({ display: 'none' });
//Click event for the pretty input and associated label.
$('#pretty_'+ id +', label[for='+ id +']').click(function() {
if (type == 'radio') {
//Radio must uncheck all related radio inputs.
$(this).siblings('span.radio.checked').removeClass('checked');
$(this).siblings('input:radio:checked').removeAttr('checked');
//And then check itself.
$('#pretty_'+ id).addClass('checked');
$('#'+ id).attr('checked', 'checked');
} else if (type == 'checkbox') {
if ($('#'+ id).attr('checked')) {
//Checkbox must uncheck itself if it is checked.
$('#pretty_'+ id).removeClass('checked');
$('#'+ id).removeAttr('checked');
} else {
//Checkbox must check itself if it is unchecked.
$('#pretty_'+ id).addClass('checked');
$('#'+ id).attr('checked', 'checked');
}
}
});
} //EOF: Radios and checkboxes.
});
});
};
This works great for the radio, but the checkbox seems to get stuck when clicking the checkbox label for a second time - the first click of the label successfully changes it to the appropriate state, but clicking the label again doesn't change it (however the checkbox itself still works fine). It works perfectly in IE8.
I've checked the id is correct and it is. I've also tried a few other methods I stumbled across of checking if the checkbox is checked, but they either gave the same result or failed altogether. :(
Any help would be much appreciated.
Thanks :)
Update
Here is the HTML, which is generated by a PHP class. This is after the jQuery has run and added in the span elements:
<div>
<p class="label">Test:</p>
<span id="pretty_test_published_field" class="checkbox"></span>
<input class="checkbox" id="test_published_field" name="test" type="checkbox" value="published">
<label for="test_published_field" class="radio">Published</label>
<span id="pretty_test_draft_field" class="checkbox"></span>
<input checked="checked" class="checkbox" id="test_draft_field" name="test" type="checkbox" value="draft">
<label for="test_draft_field" class="radio">Draft</label>
</div>
Just use the infallible and extremely simple DOM checked property. jQuery is inappropriate for this and apparently makes one of the simplest JavaScript tasks there is error-prone and confusing. This also goes for the id and type properties.
$('input', this).each(function() {
var type = this.type;
if (type == 'radio' || type == 'checkbox') {
var id = this.id;
var checked = this.checked ? 'checked' : '';
// Etc.
}
});
UPDATE
The default action of clicking a <label> element associated with a checkbox is to toggle the checkbox's checkedness. I haven't tried this myself with labels for hidden form elements, but perhaps the toggling is still happening because you're not preventing the browser's default click action. Try the following:
//Click event for the pretty input and associated label.
$('#pretty_'+ id +', label[for='+ id +']').click(function(evt) {
if (type == 'radio') {
//Radio must uncheck all related radio inputs.
$(this).siblings('span.radio.checked').removeClass('checked');
$(this).siblings('input:radio:checked').each(function() {
this.checked = false;
});
//And then check itself.
$('#pretty_'+ id).addClass('checked');
$('#'+ id)[0].checked = true;
evt.preventDefault();
} else if (type == 'checkbox') {
if ($('#'+ id).attr('checked')) {
//Checkbox must uncheck itself if it is checked.
$('#pretty_'+ id).removeClass('checked');
$('#'+ id)[0].checked = false;
} else {
//Checkbox must check itself if it is unchecked.
$('#pretty_'+ id).addClass('checked');
$('#'+ id)[0].checked = true;
}
evt.preventDefault();
}
});
i've found on the odd accassion that i need to use the alternative of:
$("#checkboxID").is(':checked');
this may or not be an alternative in your scenario, but worth noting. Also, you may have to add the 'live' event, rather than 'click' if changes to the dom are occurring. i.e.
.click(function()
to
.live('click', function()
jim
The checked attribute of a checkbox is mapped to the defaultChecked property and not to the checked property. Use the prop() method instead.
If elem is the checkbox, use:
elem.checked
or
$(elem).prop("checked")
This gives us the proper state information of the checkbox and changes as the state changes.
This seems to be the reason of confusion in many cases. So its good to keep in mind the underlying reason behind this.
Could you show us the HTML? I am looking to see if you set a value property for the checkbox in the HTML. There is a possibility that broke it.
<input type="checkbox" value="This May Break Checkbox" />
<input type="checkbox" name="This Checkbox Works" />

Categories

Resources