Automatically check a checkbox if a group of others are not checked - javascript

I'm a librarian working on improving my library's main search feature. I am trying to get a checkbox labeled "Everything" to check automatically if users deselect all of the other options ("books," "articles," "music," "videos".)
Here's the relevant javascript:
$(document).ready(function() {
var $others = $('input[class="checkoption"]').not('#everythingbox')
$others.change(function() {
if (this.checked==false) {
$('#everythingbox').prop('checked', true)
}
});
});
I almost have it working, but there's a problem: if I select two or more choices and deselect one, "Everything" checks automatically, but I only want it to check automatically if none of the others are checked.
Here is the full fiddle: https://jsfiddle.net/kr0syfn3/11/

I've edited your fiddle. You basically need to check all the other check boxes when a change happens and update the everything box accordingly.
Here's the updated fiddle jsfiddle.net/john_lay/kr0syfn3/12/
Apologies in advance for commenting out some of your code, but there was a lot of repetition. Finally you should add your change events inside the $(document).ready(function() {}); handler.

You are going to need to inspect all checkboxes each time any one of them is clicked. Right now, you are just inspecting the one single one that is clicked. To inspect all of them, you will need to use a loop (I'm using the each function in my sample below), and you might have to change your logic just a bit because you are now inspecting all items:
$(document).ready(function() {
var $others = $('input[class="checkoption"]').not('#everythingbox');
$others.change(function() {
var othersToCheck = $('input[class="checkoption"]').not('#everythingbox');
var anyChecked = false;
$.each(othersToCheck, function(index) {
if ($(this).checked) {
anyChecked=true;
}
});
$('#everythingbox').prop('checked', !anyChecked)
});
});

You could try selecting all the checkboxes that are selected and then comparing the lists, to see if all checkboxes have been selected? E.g.
var $others = $('input[class="checkoption"]').not('#everythingbox')
$others.change(function() {
var $checked = $('input[class="checkoption"]:checked').not('#everythingbox')
if ($checked.length != $others.length) { //not all the boxes are checked
$('#everythingbox').prop('checked', true)
}
}
Hope this helps!

The most concise answer to this would be to leverage the power of jQuery's built in selectors, like so:
You will also want to handle if the user selects the everything checkbox manually by clearing the rest of the selected checkboxes.
$(document).ready(function() {
var $inputs = $('input.checkoption');
$inputs.on("change", function() {
if ($(this).attr("id") !== "everythingbox") {
$('#everythingbox').prop('checked', !$('input.checkoption:not(#everythingbox):checked').length)
} else {
$inputs.not("#everythingbox").prop("checked", false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
1<input type="checkbox" class="checkoption" /> 2
<input type="checkbox" class="checkoption" /> 3
<input type="checkbox" class="checkoption" /> 4
<input type="checkbox" class="checkoption" /> everything
<input type="checkbox" class="checkoption" id="everythingbox" checked/>

var $others = $('input[class="checkoption"]').not('#everythingbox')
console.log($others)
$('#everythingbox').change(function () {
if (this.checked) {
$others.prop('checked', false)
$('#everythingbox').attr('disabled', true);
}
});
$others.change(function () {
var check = false;
var l = $others.length;
for (var i = 0; i < l; i++) {
if ($others[i].checked) {
check = true;
}
}
if (check) {
$('#everythingbox').attr('disabled', false);
$('#everythingbox').prop('checked', false);
} else {
$('#everythingbox').attr('disabled', true);
$('#everythingbox').prop('checked', true);
}
})
var music1 = $("input[id='musiccheck']");
var music2 = $("input[id='musicscores']");
music1.on('change', function () {
music2.prop('checked', this.checked);
});
music1.on('change', function () {
music2.prop('unchecked', this.unchecked);
});
$(document).ready(function () {
});

Related

How to make other JQuery run when a separate function runs?

I have the JS code below which filters based on checkboxes being checked or not (I don't think you need to see all the HTML because my question is rather simple/general, I think). All this code works fine, but I added a new function at the bottom (I noted it in the code) that simply has an uncheck all button for one of the sets of checkboxes (because there are like 30 checkboxes and I don't want the user to have to uncheck them all manually).
Anyway, the new script works properly too, except that the overall unrelated script that compares all checkboxes needs to run each time the new Uncheck All/Check All button is clicked.
Is there a simple way to make sure all the other JS runs when this new script is run?
I could be wrong, but I think I just need to somehow trigger this function inside the NEW FUNCTION:
$checkboxes.on('change', function() {
but am not sure how to do that.
ALL JS:
<script>
$(window).load(function(){
Array.prototype.indexOfAny = function(array) {
return this.findIndex(function(v) {
return array.indexOf(v) != -1;
});
}
Array.prototype.containsAny = function(array) {
return this.indexOfAny(array) != -1;
}
function getAllChecked() {
// build a multidimensional array of checked values, organized by type
var values = [];
var $checked = $checkboxes.filter(':checked');
$checked.each(function() {
var $check = $(this);
var type = $check.data('type');
var value = $check.data('value');
if (typeof values[type] !== "object") {
values[type] = [];
}
values[type].push(value);
});
return values;
}
function evaluateReseller($reseller, checkedValues) {
// Evaluate a selected reseller against checked values.
// Determine whether at least one of the reseller's attributes for
// each type is found in the checked values.
var data = $reseller.data();
var found = false;
$.each(data, function(prop, values) {
values = values.split(',').map(function(value) {
return value.trim();
});
found = prop in checkedValues && values.containsAny(checkedValues[prop]);
if (!found) {
return false;
}
});
return found;
}
var $checkboxes = $('[type="checkbox"]');
var $resellers = $('.Row');
$checkboxes.on('change', function() {
// get all checked values.
var checkedValues = getAllChecked();
// compare each resellers attributes to the checked values.
$resellers.each(function(k, reseller) {
var $reseller = $(reseller);
var found = evaluateReseller($reseller, checkedValues);
// if at least one value of each type is checked, show this reseller.
// otherwise, hide it.
if (found) {
$reseller.show();
} else {
$reseller.hide();
}
});
});
//NEW FUNCTION for "UNCHECK ALL" Button
$(function() {
$(document).on('click', '#checkAll', function() {
if ($(this).val() == 'Check All') {
$('input.country').prop('checked', true);
$(this).val('Uncheck All');
} else {
$('input.country').prop('checked', false);
$(this).val('Check All');
}
});
});
});
New button HTML for the new UNCHECK portion:
<input id="checkAll" type="button" value="Uncheck All">
I kept researching and discovered the trigger() function to handle this.
http://api.jquery.com/trigger/

how to un-check Radio Button with single click which is checked by default

I have a radio button which by default comes checked when the page loads ,and user can un_check if he want by single click but its not working in single click .. after three clicks the radio button un_checked.
Please see
JSFIDDLE . in the code the radio button with value 7 comes with checked by default , I can be able to un_check by clicking three times on it.is there any way to un_check it by just single click .Any help is appreciated.
Thank you.
<td style="padding-right:0px;"><input type="radio" name="TEST" onclick=" var allRadios = document.getElementsByName('TEST'); var booRadio; var x = 0; for(x = 0; x < allRadios.length; x++){ allRadios[x].onclick = function() { if (booRadio == this) { this.checked = false; booRadio = null; }else{ booRadio = this; } }; }" value="7" CHECKED> 7</td>
A JQuery solution, if you assing a class radioClass to your radio buttons:
(function () {
$('.radioClass').on('mouseup', function (e) {
var xRadioB = this;
if ($(xRadioB).is(':checked')) {
setTimeout(function () {
$(xRadioB).prop('checked', false);
}, 5);
}
});
})();
JSfiddle Example: https://jsfiddle.net/nfed1f7c/
First of all, I hope this is just for a test and that you will not embed events in your HTML as this will become very hard to manage, very quickly. I've manage to get a version working with some improve JavaScript. While I did not play with this for too long, I suspect there are better ways but that's a good first draft to get the results you desire: https://jsfiddle.net/0kyyfvy6/5/
var radioElements = document.querySelectorAll('input[type=radio]');
for (var iterator = 0; iterator < radioElements.length; iterator++) {
var radioElement = radioElements[iterator];
radioElement.addEventListener('mousedown', function (event) {
if (event.currentTarget.checked) {
var radioElement = event.currentTarget;
setTimeout(function () {
radioElement.checked = '';
}, 100);
}
})
}
I tried to have event.stopImmediatePropagation() and so on instead of the setTimeout but for some reasons it did not work. This seems relatively safe to implement depending on your use case.

jQuery group of checkbox issue

I have two group of checkbox newBuilding & oldBuilding.
Idea over here is I can select checkbox only one of the group.
In each group there is checkbox name other area, so I when click on it, it will show and hide textbox next to it.
Now to achieve first point, lets for example that already we have oldBuilding checkboxes are checked and I if I click one of the newBuilding checkbox then it will remove the check from oldBuilding group but newBuilding checkbox will not get checked but just get focus, I have to click again to check.
What I found out that above issue happen when I call trigger event. How can I overcome the issue
Code for other area
$("#chkOldBuildingOtherAreas").change(function () {
if ($("#chkOldBuildingOtherAreas").is(":checked"))
$("#txOldOtherAreas").show();
else
$("#txOldOtherAreas").hide();
});
$("#chkNewBuildingOtherAreas").change(function () {
if ($("#chkNewBuildingOtherAreas").is(":checked"))
$("#txNewOtherAreas").show();
else
$("#txNewOtherAreas").hide();
});
Code for removing check mark from other groups
$("input[name='oldBuilding']").change(function () {
if ($("input[name='newBuilding']:checked").length > 0) {
$("input[name='newBuilding']").removeAttr('checked');
$("#chkNewBuildingOtherAreas").trigger("change");
}
});
$("input[name='newBuilding']").change(function () {
if ($("input[name='oldBuilding']:checked").length > 0) {
$("input[name='oldBuilding']").removeAttr('checked');
$("#chkOldBuildingOtherAreas").trigger("change");
}
});
My jsfiddle
https://jsfiddle.net/milindsaraswala/wchrwjnx/
https://jsfiddle.net/1ny36nwL/4/
var groups = ['.oldGroup', '.newGroup'];
$(groups.join(',')).find('input[type=text]').hide();
function resetGroup(selector) {
//clear and hide texts
$('input[type=text]', selector).val('').hide();
//uncheck boxes
$('input[type=checkbox]', selector).removeAttr('checked');
}
$("input[name='oldBuilding']").change(function(e) {
if (this.id == 'chkOldBuildingOtherAreas') {
$("#txOldOtherAreas").toggle();
}
resetGroup('.newGroup');
});
$("input[name='newBuilding']").change(function(e) {
if (this.id == 'chkNewBuildingOtherAreas') {
$("#txNewOtherAreas").toggle();
}
resetGroup('.oldGroup');
});
as you can see I added groups var which can contain multiple groups (not only two), but code need to be changed a little more for that to work
you need to detect id/class of current group by something like $(this).closest('.form-group').id and reset every group except current group. in that way you can leave only one change function which will be universal
oh and you also need to add some class for checkbox that contain text input, and if that checkbox is clicked, trigger toggle for input. so it won't be if (this.id == 'chkNewBuildingOtherAreas') { but something like if ($(this).hasClass('has-input'))
Try replacing this in your code. It should work.
$("#txOldOtherAreas").hide();
$("#txNewOtherAreas").hide();
$("input[name='oldBuilding']").change(function (e) {
$("input[name='newBuilding']").removeAttr('checked');
e.target.checked = true;
if (e.target.id == "chkOldBuildingOtherAreas") {
$("#txOldOtherAreas").show();
$("#txNewOtherAreas").hide();
} else {
$("#txNewOtherAreas").hide();
}
});
$("input[name='newBuilding']").change(function (e) {
$("input[name='oldBuilding']").removeAttr('checked');
e.target.checked = true;
if (e.target.id == "chkNewBuildingOtherAreas") {
$("#txNewOtherAreas").show();
$("#txOldOtherAreas").hide();
} else {
$("#txOldOtherAreas").hide();
}
});
You can try following code to fix the problem (Tested in fiddle):
$('#txNewOtherAreas, #txOldOtherAreas').hide();
$('input[name="oldBuilding"]').on('click', function(){
if($('input[name="newBuilding"]').is(':checked')){
$('input[name="newBuilding"]').removeAttr('checked');
$('#txNewOtherAreas').hide();
}
});
$('input[name="newBuilding"]').on('click', function(){
if($('input[name="oldBuilding"]').is(':checked')){
$('input[name="oldBuilding"]').removeAttr('checked');
$('#txOldOtherAreas').hide();
}
});
$('#chkNewBuildingOtherAreas').on('click', function() {
if($(this).is(':checked')){
$('#txNewOtherAreas').show();
} else {
$('#txNewOtherAreas').hide();
}
});
$('#chkOldBuildingOtherAreas').on('click', function() {
if($(this).is(':checked')){
$('#txOldOtherAreas').show();
} else {
$('#txOldOtherAreas').hide();
}
});

Disable <a class button if input fields empty

I know it's easy to do using < button > or < input type="submit" but how would you keep this button disabled unless both input fields are filled?
<input id="one" type="text">
<input id="two" type="text">
OK
Tie an event to both inputs, and check that both have values. Then enable the link.
$('#one, #two').blur(function() {
if($('#one').val() !== "" && $('#two').val() !== "") {
$('.button').attr('href','#');
} else {
$('.button').removeAttr('href');
}
});
and change your html to:
<a class="button">OK</a>
so that the link is disabled on page load. Here's a JSFiddle demo.
$(document).ready(function() {
$inputs = $('#one,#tow');
$inputs.change(check);
$submit = $('#submit');
function check() {
var result = 1;
for (var i = 0; i < $inputs.length; i++) {
if (!$inputs[i].value) {
result = 0;
break;
}
}
if (result) {
$submit.removeAttr('disabled');
} else {
$submit.attr('disabled', 'disabled');
}
}
check();
});
suggest use angular form
$(document).ready(function(){
//$(".button").attr('disabled', "disabled");
$(".button").click(function(){
one = $("#one").val();
two = $("#two").val();
if(one && two){
///both fields filled.
return true;
}
//one or both of them is empty
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="one" type="text">
<input id="two" type="text">
OK
This is my implementation if facing this kind of situation.
First, am add disabled class onto anchor tag on page load by using this style :
.disabled {
color : gray // gray out button color
cursor : default; // make cursor to arrow
// you can do whatever styling you want
// even disabled behaviour
}
We add those class using jquery on document ready together with keyup event like so :
$(function () {
// add disabled class onto button class(anchor tag)
$(".button").addClass('disabled');
// register keyup handler on one and two element
$("#one, #two").keyup(function () {
var one = $("#one").val(),
two = $("#two").val();
// checking if both not empty, then remove class disabled
if (one && two) $(".button").removeClass('disabled');
// if not then add back disabled class
else $(".button").addClass('disabled');
});
// when we pressing those button
$('.button').click(function (e) {
// we check if those button has disabled class yet
// just return false
if ($(this).hasClass('disabled')) return false;
});
});
DEMO

Disable submit button until one in a group of dynamically-created radio buttons selected

I would like to disable a submit button until one of a group of radio buttons is selected. I know there are similar questions out there, but none pertain to a dynamically-created group of radio buttons...
Here is what I have.. a script at the top of the page generates a number of buttons given a user upload in a previous view:
var jScriptArray = new Array(#ViewBag.ColNames.Length);
var array = #Html.Raw(Json.Encode(ViewBag.ColNames));
for( var i = 0; i < #ViewBag.ColNames.Length; i++ ) {
jScriptArray[i] = array[i];
}
var length = #(ViewBag.NCols);
$(document).ready(function () {
for (var i = 0; i < length; i++) {
$('#radioGroupBy').append('<input id="grp' + i +'" type="radio" name="group" value="'+i+'">'+jScriptArray[i]+'</input>')
$('#radioGroupBy').append('<p style="padding:0px;margin:0px;"></br></p>');
}
});
This works, and selecting any of the buttons returns the proper value; great. However, I want to disable the submit button until one of these radio buttons is selected. Using an answer I found on SO earlier, I created the following (this works, but only if I hard code the group of buttons. The issue is it won't work with the Javascript-created group):
var $radioButtons = $("input[name='group']");
$radioButtons.change(function () {
var anyRadioButtonHasValue = false;
// iterate through all radio buttons
$radioButtons.each(function () {
if (this.checked) {
// indicate we found a radio button which has a value
anyRadioButtonHasValue = true;
// break out of each loop
return false;
}
});
// check if we found any radio button which has a value
if (anyRadioButtonHasValue) {
// enable submit button.
$("input[name='submitbtn']").removeAttr("disabled");
}
});
Also, for the sake of thoroughness, here is the submit button:
<input id="submitbtn" name="submitbtn" type="submit" value="Drill Down" disabled="disabled" />
Thanks so much!
Event delegation (also, use .prop() when removing the disabled property to the submit button)
$("#radioGroupBy").on("change", ":radio[name=group]", function() {
var $radioButtons = $(":radio[name=group]");
var anyRadioButtonHasValue = false;
// iterate through all radio buttons
$radioButtons.each(function () {
if (this.checked) {
// indicate we found a radio button which has a value
anyRadioButtonHasValue = true;
// break out of each loop
return false;
}
});
// check if we found any radio button which has a value
if (anyRadioButtonHasValue) {
$("input[name='submitbtn']").prop("disabled", false);
}
});
I figured it out. As Benjamin suggested in comments above, the latter script was executing before the DOM was ready. I solved it by just surrounding the whole script in $(window).load... :
$(window).load(function () {
var $radioButtons = $("input[name='group']");
$radioButtons.change(function () {
var anyRadioButtonHasValue = false;
// iterate through all radio buttons
$radioButtons.each(function () {
if (this.checked) {
// indicate we found a radio button which has a value
anyRadioButtonHasValue = true;
// break out of each loop
return false;
}
});
// check if we found any radio button which has a value
if (anyRadioButtonHasValue) {
// enable submit button.
$("input[name='submitbtn']").removeAttr("disabled");
}
});
});

Categories