Making two exclusive checkbox inside div - javascript

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

Related

jQuery toggle checkbox and also toggle anchor text

I have a checkbox as follows:
<div class="left-col">
.......
<div class="actors-top sel-actors">
<p class="selall sel-actors"><a class="sel-actors" id=""seltext>Select all Actors</a></p>
<input type="checkbox" name="" value="" class="chk1" class="sel-actors" />
</div>
.......
</div>
I want the whole space of the div sel-actors control the checkbox checked and not checked. When Select all Actors is clicked I want all checkboxes on the left-col to be checked and the text Select all Actors to be changed into Deselect all Actors. On the click back i want it to go back to how it was.
After checking out stackoverflow i found something that checks the checkbox but doesnt toggle text with it:
$(document).ready(function() {
$(".sel-actors").click(function() {
var checkBoxes = $(".left-col input");
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
});
});
I would like this to toggle text also.
Here is what you want.
$(document).ready(function() {
var SEL_ACTORS_TEXT = {
CHECKED: 'Deselect all Actors',
UNCHECKED: 'Select all Actors'
};
$(".sel-actors").click(function() {
var checkBoxes = $(".left-col input"),
$this = $(this);
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
if ($this.prop('checked')) {
$this.text(SEL_ACTORS_TEXT.CHECKED);
} else {
$this.text(SEL_ACTORS_TEXT.UNCHECKED);
}
});
});
Basically, add a variable to store the potential text strings and then after updating the checkboxes, set the string accordingly.
Hope this helps!
Try this:
$('.sel-actors').text('Deselect all Actors');
EDIT: to incorporate it into your function, do this:
$(document).ready(function() {
$(".sel-actors").click(function() {
var checkBoxes = $(".left-col input");
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
if($('chk1').is(':checked'))
$(this).text('Deselect all Actors');
else
$(this).text('Select all Actors');
});
});
EDIT #2: note that you have defined the class property twice for your checkbox; try either merging them or maybe setup chk1 as an id instead, then you'd call it like this: $('#chk1'). You may also want to add an id for your anchor holding the text to differentiate it from the checkbox; modify the function accordingly, of course.
EDIT #3: Here is the cleaned up code:
$(document).ready(function() {
$("#chk1").click(function() {
var checkBoxes = $(".left-col input");
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
if($(this).is(':checked'))
$('#seltext').text('Deselect all Actors');
else
$('#seltext').text('Select all Actors');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="sel-actors" id="seltext">Select all Actors</a>
<input type="checkbox" name="" value="" id="chk1" class="sel-actors" />
Try the following.
<script type="text/javascript">
$('.sel-actors').click(function (event) {
if (this.checked) {
$('.chk1').each(function () {
$('.sel-actors').val("De-select all Actors");
this.checked = true;
});
} else {
$('.chk1').each(function () {
$('.sel-actors').val("Select all Actors");
this.checked = false;
});
}
});
</script>

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

hide div when no checkbox is checked

I am trying to show hidden text if at least one checkbox is checked and hide it if none are checked. I have a multiple checkboxes.The hidden text isn't showing when I check the checkooxes. Any help?
Here is fiddle http://jsfiddle.net/HDGJ9/1/
<input type="checkbox" name="ch[]">
<input type="checkbox" name="ch[]">
<input type="checkbox" name="ch[]">
<input type="checkbox" name="ch[]">
<div class="txt" style="display:none">
if($('input[name="ch[]"]').is(':checked'))
$(".txt").show(); // checked
else
$(".txt").hide(); // unchecked
Enclose/wrap your code with event handler like
$('input[name="ch[]"]').on('change', function () {
//your code
});
JSFiddle
You can just check the length of checked checkboxes...
var $checkboxes = $(':checkbox');
$checkboxes.on('change', function(){
$('.txt').toggle( $checkboxes.filter(':checked').length > 0 );
});
Nothing is executing your javascript code. There are many ways to execute, and also many ways to achieve the result you want. You can assign it to a click or change event like so:
$("input[name='ch[]']").click(function() {
if($('input[name="ch[]"]').is(':checked'))
$(".txt").show(); // checked
else
$(".txt").hide(); // unchecked
});
Here is an updated fiddle that checks your function everytime you click.
In your code, the test for checked/unchecked boxes occurs only once, when the page loads. You should run this check every time the value of any of the checkboxes changes. Something like
function refresh() {
if ($('input[name="ch[]"]').is(':checked')) {
$(".txt").show(); // checked
} else {
$(".txt").hide(); // unchecked
}
}
$('input:checkbox').change(refresh);
JSFiddle: http://jsfiddle.net/MHB8q/1/
You are selecting all four checkbox elements here, you need to only select one that is checked, and see if you get a result:
if($('input[name="ch[]"]').filter(':checked').length){
$(".txt").show(); // checked
} else {
$(".txt").hide(); // unchecked
}
Demo: http://jsfiddle.net/HDGJ9/10/
$('input[name="ch[]"]').on('change', function() {
if ($(this).is(':checked')) {
$('.txt').css('display', 'block');
}
else {
var checked = false;
$('input[name="ch[]"]').each(function(i, el) {
if ($(el).is(':checked')) checked = true;
});
if (!checked) $('.txt').css('display', 'none');
}
});
Version with the least amount of event handlers:
$(document).on("change", ":checkbox", function(){
var isAtLeastOneCheckboxChecked = $(':checkbox').filter(":checked").length > 0;
if (isAtLeastOneCheckboxChecked)
$('.txt').show();
else
$('.txt').hide();
});
Fiddle: http://jsfiddle.net/3d79N/

Click checkbox based on label name

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

jquery select all checkboxes

I have a series of checkboxes that are loaded 100 at a time via ajax.
I need this jquery to allow me to have a button when pushed check all on screen. If more are loaded, and the button is pressed, to perhaps toggle all off, then pressed again toggle all back on.
This is what i have, obviously its not working for me.
$(function () {
$('#selectall').click(function () {
$('#friendslist').find(':checkbox').attr('checked', this.checked);
});
});
The button is #selectall, the check boxes are class .tf, and they all reside in a parent div called #check, inside a div called #friend, inside a div called #friendslist
Example:
<div id='friendslist'>
<div id='friend'>
<div id='check'>
<input type='checkbox' class='tf' name='hurr' value='durr1'>
</div>
</div>
<div id='friend'>
<div id='check'>
<input type='checkbox' class='tf' name='hurr' value='durr2'>
</div>
</div>
<div id='friend'>
<div id='check'>
<input type='checkbox' class='tf' name='hurr' value='durr3'>
</div>
</div>
</div>
<input type='button' id='selectall' value="Select All">
I know I'm revisiting an old thread, but this page shows up as one of the top results in Google when this question is asked. I am revisiting this because in jQuery 1.6 and above, prop() should be used for "checked" status instead of attr() with true or false being passed. More info here.
For example, Henrick's code should now be:
$(function () {
$('#selectall').toggle(
function() {
$('#friendslist .tf').prop('checked', true);
},
function() {
$('#friendslist .tf').prop('checked', false);
}
);
});
$('#friendslist .tf')
this selector will suit your needs
Use the jquery toggle function. Then you can also perform whatever other changes you may want to do along with those changes... such as changing the value of the button to say "check all" or "uncheck all".
$(function () {
$('#selectall').toggle(
function() {
$('#friendslist .tf').attr('checked', 'checked');
},
function() {
$('#friendslist .tf').attr('checked', '');
}
);
});
A very simple check/uncheck all without the need of loop
<input type="checkbox" id="checkAll" /> Check / Uncheck All
<input type="checkbox" class="chk" value="option1" /> Option 1
<input type="checkbox" class="chk" value="option2" /> Option 2
<input type="checkbox" class="chk" value="option3" /> Option 3
And the javascript (jQuery) accounting for "undefined" on checkbox value
** UPDATE - using .prop() **
$("#checkAll").change(function(){
var status = $(this).is(":checked") ? true : false;
$(".chk").prop("checked",status);
});
** Previous Suggestion - may not work **
$("#checkAll").change(function(){
var status = $(this).attr("checked") ? "checked" : false;
$(".chk").attr("checked",status);
});
OR with the suggestion from the next post using .prop() combined into a single line
$("#checkAll").change(function(){
$(".chk").attr("checked",$(this).prop("checked"));
});
This is how I toggle checkboxes
$(document).ready(function() {
$('#Togglebutton').click(function() {
$('.checkBoxes').each(function() {
$(this).attr('checked',!$(this).attr('checked'));
});
});
});
maybe try this:
$(function () {
$('#selectall').click(function () {
$('#friendslist .tf').attr('checked', this.checked);
});
});
<div class="control-group">
<input type="checkbox" class="selAllChksInGroup"> All
<input type="checkbox" value="NE"> Nebraska
<input type="checkbox" value="FL"> Florida
</div>
$(document).ready(function(){
$("input[type=checkbox].selAllChksInGroup").on("click.chkAll", function( event ){
$(this).parents('.control-group:eq(0)').find(':checkbox').prop('checked', this.checked);
});
});
I could not get this last example to work for me. The correct way to query the state of the checkbox is apparently :
var status = $(this).prop("checked");
and not
var status = $(this).attr("checked") ? "checked" : false;
as above.
See jQuery receiving checkbox status
It works for me (IE, Safari, Firefox) by just changing your this.checked to 'checked'.
$(function() {
$('#selectall').click(function() {
$('#friendslist').find(':checkbox').attr('checked', 'checked');
});
});
You may try this:
$(function () {
$('#selectall').click(function () {
$('#friendslist input:checkbox').attr('checked', checked_status);
});
});
//checked_status=true/false -as the case may be, or set it via a variable
assuming #selectall is a checkbox itself whose state you want copied to all the other checkboxes?
$(function () {
$('#selectall').click(function () {
$('#friendslist input:checkbox').attr('checked', $(this).attr('checked'));
});
});
try this
var checkAll = function(){
var check_all = arguments[0];
var child_class = arguments[1];
if(arguments.length>2){
var uncheck_all = arguments[2];
$('#'+check_all).click(function (){
$('.'+child_class).attr('checked', true);
});
$('#'+uncheck_all).click(function (){
$('.'+child_class).attr('checked', false);
});
$('.'+child_class).click(function (){
var checkall_checked = true;
$('.'+child_class).each(function(){
if($(this).attr('checked')!=true){
checkall_checked = false;
}
});
if(checkall_checked == true){
$('#'+check_all).attr('checked', true);
$('#'+uncheck_all).attr('checked', false);
}else{
$('#'+check_all).attr('checked', false);
$('#'+uncheck_all).attr('checked', true);
}
});
}else{
$('#'+check_all).click(function (){
$('.'+child_class).attr('checked', $(this).attr('checked'));
});
$('.'+child_class).click(function (){
var checkall_checked = true;
$('.'+child_class).each(function(){
if($(this).attr('checked')!=true){
checkall_checked = false;
}
});
$('#'+check_all).attr('checked', checkall_checked);
});
}
};
To "check all" and "uncheck all" is same checkbox
checkAll("checkall_id", "child_checkboxes_class_name");
To "check all" and "uncheck all" is separate checkbox
checkAll("checkall_id", "child_checkboxes_class_name", "uncheckall_id");
Here is how I achieved it.
function SelectAllCheckBoxes();
{
$('#divSrchResults').find(':checkbox').attr('checked', $('#chkPrint').is(":checked"));
}
The following fires the above line.
<input type=checkbox id=chkPrint onclick='SelectAllCheckBoxes();' />
On the click of chkPrint , every checkbox in the grid divSrchResults' is either checked or unchecked depending on the status of chkPrint.
Of course, if you need advanced functions like unchecking the titled checkbox when every other checkbox has been unchecked, you need to write another function for this.
I created a function that I use on all projects. This is just the initial draft, but maybe it will help:
Function:
function selectAll(wrapperAll, wrapperInputs) {
var selectAll = wrapperAll.find('input');
var allInputs = wrapperInputs.find('input');
console.log('Checked inputs = ' + allInputs.filter(':not(:checked)').length);
function checkitems(allInputs) {
//If all items checked
if (allInputs.filter(':not(:checked)').length === 0) {
console.log('Function: checkItems: All items checked');
selectAll.attr('checked', true);
} else {
console.log('Function: checkItems: Else all items checked');
selectAll.attr('checked', false);
}
}
checkitems(allInputs);
allInputs.on('change', function () {
checkitems(allInputs)
});
selectAll.on('change', function () {
if (this.checked) {
console.log('This checkbox is checked');
wrapperInputs.find(':checkbox').attr('checked', true);
} else {
console.log('This checkbox is NOT checked');
wrapperInputs.find(':checkbox').attr('checked', false);
}
});
}
It accepts the 2 parameters where the inputs are wrapped into and you cand use-it like this:
$(function () {
var wrapperAll = $('.selectallinput');
var wrapperInputs = $('.inputs');
selectAll(wrapperAll, wrapperInputs);
});
See demo: http://jsfiddle.net/cHD9z/
So "checked" is a crappy attribute; in many browsers it doesn't work as expected :-( Try doing:
$('#friendslist').find(':checkbox')
.attr('checked', this.checked)
.attr('defaultChecked', this.checked);
I know setting "defaultChecked" doesn't make any sense, but try it and see if it helps.
<input type="checkbox" onclick="toggleChecked(this.checked)"> Select / Deselect All
Now here are two versions of the toggleChecked function dependent on the semantics of your document. The only real difference is the jQuery selector for your list checkboxes:
1: All checkboxes have a class of “checkbox” (<input type=”checkbox” class=”checkbox” />)
function toggleChecked(status) {
$(".checkbox").each( function() {
$(this).attr("checked",status);
})
}
2: All the checkboxes are contained within a div with an arbitary id:
<div id="checkboxes">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
In this case the function would look like this:
function toggleChecked(status) {
$("#checkboxes input").each( function() {
$(this).attr("checked",status);
})
Have fun!
This may work for both (checked/unchecked) selectall situations:
$(document).ready(function(){
$('#selectall').click(function () {
$("#friendslist .tf").attr("checked",function(){return $(this).attr("checked") ? false : true;});
});
});
The currently accepted answer won't work for jQuery 1.9+. The event handling aspect of the (rather heavily) overloaded .toggle() function was removed in that version, which means that attempting to call .toggle(function, function) will instead just toggle the display state of your element.
I'd suggest doing something like this instead:
$(function() {
var selectAll = $('#selectall');
selectAll.on('click', function(e) {
var checked = !(selectAll.data('checked') || false);
$('#friendslist .tf').prop('checked', checked);
selectAll.data('checked', checked);
});
});
That uses a regular click event handler, plus a data attribute to track the "toggled" status and invert it with each click.
Here's a basic jQuery plugin I wrote that selects all checkboxes on the page, except the checkbox/element that is to be used as the toggle. This, of course, could be amended to suit your needs:
(function($) {
// Checkbox toggle function for selecting all checkboxes on the page
$.fn.toggleCheckboxes = function() {
// Get all checkbox elements
checkboxes = $(':checkbox').not(this);
// Check if the checkboxes are checked/unchecked and if so uncheck/check them
if(this.is(':checked')) {
checkboxes.prop('checked', true);
} else {
checkboxes.prop('checked', false);
}
}
}(jQuery));
Then simply call the function on your checkbox or button element:
// Check all checkboxes
$('.check-all').change(function() {
$(this).toggleCheckboxes();
});
As you are adding and removing more checkboxes via AJAX, you may want to use this instead of .change():
// Check all checkboxes
$(document).on('change', '.check-all', function() {
$(this).toggleCheckboxes();
});

Categories

Resources