Multieple CheckBoxes dynamically check uncheck based on selected checkbox + MVC3 + jQuery/Javascript - javascript

I have a HTML form with checkboxes as below,
when I select ALL, other check boxes {HR, FINANCE, IT, SALES} should get checked
When I un select ALL, other checkboxes {HR, FINANCE, IT, SALES} should get unchecked
When everything is checked and of one the checkboxes {HR, FINANCE, IT, SALES} is unchecked, ALL should be unchecked
Below is the markup of my HTML.... how can I so it using jQuery/javascript ????
<input type="checkbox" name="Dept" value="ALL"/>
<input type="checkbox" name="Dept" value="HR"/>
<input type="checkbox" name="Dept" value="FINANCE"/>
<input type="checkbox" name="Dept" value="IT"/>
<input type="checkbox" name="Dept" value="SALES"/>

Try this
jQuery > 1.6
// Cache the selectors as they are being multiple times
var $all = $('input[value=ALL]'),
$inputs = $('input');
$all.change(function () {
// Set the other inputs property to the all checkbox
$inputs.not(this).prop('checked', this.checked);
});
// Change event for all other inputs
$inputs.not($all).change(function () {
var $others = $inputs.not($('input[value=ALL]'));
// Get the checked checkboxes
var $checked = $others.filter(function () {
return this.checked;
});
// If length is not equal then uncheck the All checkbox
if ($others.length !== $checked.length) {
$all.prop('checked', false);
}
});
jQuery 1.4.4
var $all = $('input[value=ALL]'),
$inputs = $('input');
$all.change(function () {
var allChk = this;
$inputs.each(function() {
this.checked = allChk.checked;
});
});
$inputs.not($('input[value=ALL]')).change(function () {
var $others = $inputs.not($('input[value=ALL]'));
var $checked = $others.filter(function () {
return this.checked;
});
if ($others.length !== $checked.length) {
$all[0].checked = false;
}
});
jQuery > 1.6 Fiddle
jQuery 1.4.4 Fiddle

Try this,
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
where case is the class added to othe check boxes
For online demo visit,
http://viralpatel.net/blogs/multiple-checkbox-select-deselect-jquery-tutorial-example/

DEMO
$('input[type="checkbox"][name="Dept"]').change(function () {
if (this.value == 'ALL') {
$('input[name="Dept"]').prop('checked', this.checked);
}
});
Updated Demo with jQuery 1.5.2
$('input[type="checkbox"][name="Dept"][value="ALL"]').change(function () {
$('input[name="Dept"]').attr('checked', this.checked);
});
$('input[type="checkbox"][name="Dept"]:gt(0)').change(function () {
if (!this.checked) {
$('input[name="Dept"][value="ALL"]').removeAttr('checked');
}
if ($('input[type="checkbox"][name="Dept"]:gt(0)').length == $('input[type="checkbox"][name="Dept"]:gt(0):checked').length) {
$('input[type="checkbox"][name="Dept"][value="ALL"]').attr('checked',true);
}
});

Here's one way to do it:
$(document).ready(function() {
var $cbs = $('input[name="Dept"]').click(function() {
if (this.value==="ALL")
$cbs.prop("checked", this.checked);
else if (!this.checked)
$cbs[0].checked = false;
});
});
Jawdroppingly good demo: http://jsfiddle.net/MNbDw/2/
Note that obviously my code above has a hardcoded assumption that the "ALL" checkbox will be the first one (at the point where I unchecked it using $cbs[0]). You could change the else if case to do this instead:
$cbs.filter('[value="ALL"]').prop("checked",false);
Demo: http://jsfiddle.net/MNbDw/3/
Or change your html to give that particular checkbox an id or whatever.
UPDATE: The .prop() method was introduced in jQuery 1.6. For version 1.5.2 (as mentioned in a comment) use .attr() instead as shown here (though 1.5.2 is so old that jsfiddle doesn't actually offer it as an option so I had to add it under "External Resources"): http://jsfiddle.net/MNbDw/9/

Related

jQuery/js Removing a dynamically created checkbox

I'm using Eric Hynds jQuery MultiSelect Widget that is being populated from a javascript file. A checkbox is created with label attached under a 'Main' checkbox if a Main is checked. How can I set it up to where the dynamically created checkbox removes if that corresponding Main is unchecked? Please see my fiddle to illustrate my problem http://jsfiddle.net/3u7Xj/76/
$(document).ready(function() {
$(".multiselect").multiselect({
header: "Choose up to 5 areas total",
click: function (event, ui) {
var number1=$("#dropdown1").children(":checked").length,
number2=$("#dropdown2").children(":checked").length;
if (ui.checked && ((number1 + number2 >=2) || $(this).children(":checked").length >= 2)) {
return false;
}
var lbl = ui.value;
if(ui.checked){
var ctrl = '<input type="checkbox" name="chk" checked="checked" class="chk" id="'+lbl+'">';
$("[id^=Main]:checked").each(function(){
$(this).nextAll('.holder:first').append('<div>'+ctrl+lbl+'</div>');
});
}
else {
$("[id^=Main]:checked").each(function(){
$(this).nextAll('.holder:first').find('div input[id="'+lbl+'"]').parent().remove();
});
}
},
selectedList:5
});
});
Something like this?
$("[id^=id]:checked",false).each(function(){
$(this).nextAll('.holder:first').find('div input[id="'+lbl+'"]').parent().remove();
});
Or
if(ui.checked = false){
$(this).nextAll('.holder:first').find('div input[id="'+lbl+'"]').parent().remove();
}
else{};
how about adding this?
$("input[name^=chkMain]").change(function(){
if($(this).not(':checked')){
$(this).next('label').next('.holder').html('');
}
});
http://jsfiddle.net/3u7Xj/77/
is that what you meant?
Try this
else {
$("[id^=Main]:checked").each(function(){
$(this).nextAll('.holder:first').find('#' + lbl).parent().remove();
})
}
Demo
I also added a functionality that unchecks the children of a main if it is unchecked. Remove the code
$(".checkers").click(function() {
if(!$(this).is(':checked')) {
$(this).nextAll('.holder:eq(0)').find('div input').attr("checked", this.checked);
}
});
if you don't want that functionality. You could also change .attr("checked", this.checked) to .parent().remove() if you wanted to remove the check boxes instead
If you wanted to do the opposite, meaning check the boxes then the Main, you could use the following
var checkedOnes = $('#dropdown1').nextAll('.ui-multiselect-menu').find('ul li input:checked');
for(var i = 0; i < checkedOnes.length; i++) {
var lbl = checkedOnes.eq(i).attr('value');
var ctrl = '<input type="checkbox" name="chk" checked="checked" class="chk" id="'+lbl+'">';
$("[id^=Main]:checked").each(function(){
$(this).nextAll('.holder:first').append('<div>'+ctrl+lbl+'</div>');
});
}
Updated Demo

checkbox inside div. On click checked or unchecked using jquery 1.9.1

Hi i want to make checkbox checked or unchecked when i click div with text. Using jquery 1.9.1
here is a link to js fiddle
<div class="tel_show">
<input type="checkbox" name="whatever" />
visible
</div>
$("div.tel_show").live("click",function(event) {
var target = $(event.target);
if (target.is('input:checkbox')) return;
var checkbox = $(this).find("input[type='checkbox']");
if( checkbox.attr("checked") == "" ){
checkbox.attr("checked","true");
} else {
checkbox.attr("checked","");
}
});
js fiddle link
The use of .live() is deprecated on jQuery 1.9.x , also the use of checked html attribute to toggle checkboxes is deprecated, use .prop('checked') instead, your updated code should be:
$("div.tel_show").on("click",function(event) {
var target = $(event.target);
if (target.is('input:checkbox')) return;
var checkbox = $(this).find("input[type='checkbox']");
if( !checkbox.prop("checked") ){
checkbox.prop("checked",true);
} else {
checkbox.prop("checked",false);
}
});
see working fiddle
use .prop() instead of .attr() and .live() is removed in 1.9, use .on() instead
$(document).on("click", "div.tel_show", function (event) {
var target = $(event.target);
if (target.is('input:checkbox')) {
return;
}
var checkbox = $(this).find("input[type='checkbox']");
checkbox.prop("checked", !checkbox.is(':checked'));
});
Demo: Fiddle

Jquery check if radio button is checked

I am trying to uncheck a radio button if it is checked, and likewise check a radio button if it is unchecked. However, it is always saying it is checked when it isn't.
Here is my code:
$('input[type=radio]').on('click', function() {
if ($(this).attr('checked') == 'checked') {
$(this).attr('checked', false);
} else {
$(this).attr('checked', true);
}
});
The above code always hits the first part of the if. I've also tried
$(this).is(':checked')
and
$(this).val()
and
$(this).attr('checked') == true
but nothing seems to be working.
How can I get this to work?
Here is the fiddle hope this myt help:
<input type="radio" name="" value="1000" align="middle" id="private_contest">1000 is the value<br>
<input type="radio" name="" value="2000" align="middle" id="private_contest">2000 is the value
and relevant jquery is:
$('input[type=radio]').on('click', function () {
$(this).siblings().prop('checked', true);
$(this).prop('checked', false);
});
You need to remove the attribute checked to uncheck, and add the attribute to check the radio button. Do not assign value to it:
<input type="radio" name="radio1">
<input type="radio" name="radio1" checked>
use:
$(this).addAttr("checked")
$(this).removeAttr("checked")
This should never fail, but it's a different approach.
Target the parent, and return which radio IS checked, rather than looking at all of them.
Just an idea
var myRadio;
$('#radioParent input:radio').click(function() {
myRadio = $(this).attr('id');
//console.log(myRadio);
//return myRadio;
});
I am not sure why this received negative votes. The usage of a radio button is so that you can have 0 or 1 options to select from, and a checkbox list is if you need 0 or many options selected. But what if you want to undo a radio button selection for an optional question?
I solved this by creating another attribute on radio buttons called "data-checked".
Below was the implementation:
$('input[type=radio]').on('click', function() {
var radioButton = $(this);
var radioButtonIsChecked = radioButton.attr('data-checked') == 'true';
// set 'checked' to the opposite of what it is
setCheckedProperty(radioButton, !radioButtonIsChecked);
// you will have to define your own getSiblingsAnswers function
// as they relate to your application
// but it will be something similar to radioButton.siblings()
var siblingAnswers = getSiblingAnswers(radioButton);
uncheckSiblingAnswers(siblingAnswers);
});
function uncheckSiblingAnswers(siblingAnswers) {
siblingAnswers.each(function() {
setCheckedProperty($(this), false);
});
}
function setCheckedProperty(radioButton, checked) {
radioButton.prop('checked', checked);
radioButton.attr('data-checked', checked);
}
On the page load, set the data-checked property to true or false, depending on whether or not it is already checked.
$(document).ready(function() {
$('input[type=radio]').each(function () {
var radioButton = $(this);
var radioButtonIsChecked = radioButton.attr('checked') == 'checked';
setCheckedProperty(radioButton, radioButtonIsChecked);
});
});

Select one option from each combobox

I have 6 html selects on a form, each of which contains the same 8 options.
If an option has been chosen from one of the selects, then I'd like that option to be disabled in all other selects. I'd like the option to still be visible (i.e. it must not be removed).
Is there a jquery plugin or similar that can be used?
Try it here: http://jsfiddle.net/jbjkm/3/
$.fn.exclusiveSelectSet = function() {
var set = this, options = this.find('option');
return this.change(function() {
var selected = {};
set.each(function(){ selected[this.value] = true });
options.each(function() {
var sel = this.parentNode;
this.disabled = this.value && selected[this.value] &&
sel.options[sel.selectedIndex] != this;
});
}).change();
}
$('select.loves').exclusiveSelectSet();
$('#likes select').exclusiveSelectSet();
In English, whenever a select value is changed:
Find the values of all selected options.
Disable any option that has one of the selected values,
unless it doesn't have any value (value="") or it is the selected option in its <select>.
to disable/enable all other checkboxes with the same value add this Javascript:
$(document).ready(function(){
$('input[tpye="checkbox"]').change(function(){
if($(this).is(':checked'))
$('input[value="'.$(this).val().'"]').each(function(){
$(this).attr('disabled', true);
});
else
$('input[value="'.$(this).val().'"]').each(function(){
$(this).removeAttr('disabled');
});
});
});
if u use selects try this:
$(document).ready(function(){
$('select').change(function(){
$('option:disabled').each(function(){
$(this).removeAttr('disabled');
});
$('select').each(function(){
var v = $(this).val();
$('option[value="'+v+'"]').each(function(){
if($(this).parent() != $(this))
$(this).attr('disabled',true);
});
});
});
});
EDIT: ah, right, enable all option before disabling some (reset)

How to restore Textbox Data

I have a small requirement,
We have restore the textbox data that was cleared previously.
Below is my HTMl code
<table>
<tr><td><input type="textbox"></td></tr>
<tr><td><input type="checkbox"></td></tr>
</table>
Here is my JQuery Code
$('TABLE TR TD').find(':checkbox').change(function()
{
if($(this).prop('checked'))
{
$(this).parents('TR').siblings('TR').find('input').val("")
}
if(!$(this).prop('checked'))
{
$(this).parents('TR').siblings('TR').find('input').val(?)
}
});
My Requirement is to clear the textbox content if checkbox is checked. And if i deselect it the textbox should be restored with previous data.
Please someone help me.
Use a global variable to store the previous data -
var prevData;
then modify your code this way -
$('TABLE TR TD').find(':checkbox').change(function()
{
if($(this).prop('checked'))
{
var $element = $(this).parents('TR').siblings('TR').find('input')
prevData = $element.val();
$element.val("");
}
else
{
$(this).parents('TR').siblings('TR').find('input').val(prevData);
}
});
When the checkbox is being checked, before clearing the value, store it using the jQuery .data() API.
<table>
<tr><td><input type="text"></td></tr>
<tr><td><input type="checkbox"></td></tr>
</table>
$('input:checkbox').change(function() {
var input = $(this).closest('table').find('input[type="text"]');
if ($(this).prop('checked')) {
input.data('text', input.val());
input.val('');
} else {
input.val(input.data('text'));
}
});
A demo which works if there were multiple pairs, so long as they exist in separate <table> parents. You could change the finder to get the previous sibling if that were not the case. This uses no global variables which are not really best practice - How to avoid global variables in JavaScript?.
Edit: Updated demo based on your other question Keydown event is not working properly but this will only for key events and not if someone pastes text into the <input>.
I'd suggest something a little less reliant on the mark-up remaining the same (though it does require that the checkbox follows the text input):
var prevData, textInputIndex;
$('input:checkbox').change(
function(){
thisIndex = ($(this).index('table input') - 1);
textInput = $('table input').eq(thisIndex);
if ($(this).is(':checked')) {
prevData = $(textInput).eq(thisIndex).val();
$(textInput).eq(thisIndex).val('');
}
else {
$(textInput).eq(thisIndex).val(prevData);
}
});
JS Fiddle demo.
Edited to remove the problem of having only one variable to store the text-input value:
var $textInputs = $('table input:text');
var prevData, textInputIndex, affectedTextInputIndex, textInputValues = [];
$('input:checkbox').change(
function(){
affectedTextInputIndex = $(this).index('table input') - 1;
textInputIndex = $('table input').eq(affectedTextInputIndex).index('table input:text');
if ($(this).is(':checked')) {
textInputValues[textInputIndex] = $textInputs.eq(textInputIndex).val();
$textInputs.eq(textInputIndex).val('');
}
else {
$textInputs.eq(textInputIndex).val(textInputValues[textInputIndex]);
}
});
JS Fiddle demo.
Edited to remove the explicit requirement that the input elements be contained in a table:
var $textInputs = $('input:text');
var prevData, textInputIndex, affectedTextInputIndex, textInputValues = [];
$('input:checkbox').change(
function(){
affectedTextInputIndex = $(this).index('input') - 1;
textInputIndex = $('ul input').eq(affectedTextInputIndex).index('input:text');
if ($(this).is(':checked')) {
textInputValues[textInputIndex] = $textInputs.eq(textInputIndex).val();
$textInputs.eq(textInputIndex).val('');
}
else {
$textInputs.eq(textInputIndex).val(textInputValues[textInputIndex]);
}
});
JS Fiddle demo.
References:
:checkbox selector.
change().
is().
:checked selector.
index().
val().

Categories