.checked always returns true? - javascript

I'm using vanilla js, and I'm stumped because there's very little code here, so I'm not sure where the problem lies. It may be a misunderstanding on my part on how the attribute works.
function changeState() {
const self = event.target
const parent = event.path[1]
if (self.type == "radio") {
console.log(self.id + " is " + self.checked)
}
}
<div id="usernames_buttons">
<input type="radio" name="usernames" id="usernames-bl" onclick="changeState()" checked>
<label for="usernames-bl">BL</label>
</input>
<input type="radio" name="usernames" id="usernames-wl" onclick="changeState()">
<label for="usernames-wl">WL</label>
</input>
<button data-toggle onclick="changeState()">OFF</button>
</div>
I paired everything down to just this code and ran it in a code pen to test, and the console.log will return true regardless of which option I am clicking. The expectation is that usernames-bl would return true and -wl would return false, but they return true whether the checked attribute is there or not.

You are invoking the changeState() on every click and i guess, as its a radio button, which will always give checked 'true' on click

I think you are doing it right minus the "Off" button should un-check both.. so I added this block:
if (self.type != "radio") {
document.getElementById("usernames-wl").checked = false;
document.getElementById("usernames-bl").checked = false;
}
function changeState() {
const self = event.target
const parent = event.path[1]
if (self.type != "radio") {
document.getElementById("usernames-wl").checked = false;
document.getElementById("usernames-bl").checked = false;
}
console.log("usernames-wl is " + document.getElementById("usernames-wl").checked)
console.log("usernames-bl is " + document.getElementById("usernames-bl").checked)
}
<div id="usernames_buttons">
<input type="radio" name="usernames" id="usernames-bl" onclick="changeState()" checked/>
<label for="usernames-bl">BL</label>
<input type="radio" name="usernames" id="usernames-wl" onclick="changeState()"/>
<label for="usernames-wl">WL</label>
<button data-toggle onclick="changeState()">OFF</button>
</div>

Related

How to show div, if one of the checkboxes is checked (with a different name on each checkbox)?

I am trying to show div if one of the two checkboxes is checked. I found it in some article but with the same name, I am using a different name for each checkbox to store it into mysql. My current javascript code is
document.addEventListener('change', function(jj) {
function jj() {
if ((document.getElementById('jj1_ikk').checked) || (document.getElementById('jj2_ikk').checked)) {
document.getElementById('jsa').style.display="block";
} else {
document.getElementById('jsa').style.display="none";
}
}
})
the input fields are
<input type="checkbox" id="jj1_ikk" name="jj1_ikk" /><label for="jj1_ikk">A</label>
<input type="checkbox" id="jj2_ikk" name="jj2_ikk" /><label for="jj2_ikk">B</label>
where jj1_ikk and jj2_ikk are the checkboxes id, and jsa is the div that I want to do show/hide.
I hope my description is clear, thank you.
You can put two check box in span and check changes onclick span like this
HTML
<span onclick="CheckChanges()">
<input type="checkbox" id="jj1_ikk" name="jj1_ikk" /><label for="jj1_ikk">A</label>
<input type="checkbox" id="jj2_ikk" name="jj2_ikk" /><label for="jj2_ikk">B</label>
</span>
<div id="jsa">This is the element that will be shown if both checkboxes aren't checked</div>
JavaScript
var aCheckBox = document.getElementById("jj1_ikk")
var bCheckBox = document.getElementById("jj2_ikk")
function CheckChanges() {
if (aCheckBox.checked == true || bCheckBox.checked == true) {
document.getElementById("jsa").style.display = "block"
} else {
document.getElementById("jsa").style.display = "none"
}
}
You did a mistake when adding the handler for the change event defining two nested functions. Plus I added the event handler only once the document was loaded. You can test the code in this snippet:
//when the document has been loaded, adds the event handlers to the checkboxes
document.addEventListener("DOMContentLoaded", () => {
document.addEventListener('change', () => addHandlers());
});
/**
* Adds handler for the change event on both checkboxes
*/
function addHandlers(){
let jj1 = document.getElementById('jj1_ikk');
let jj2 = document.getElementById('jj2_ikk');
jj1.addEventListener('change', updateMsgVisibility);
jj2.addEventListener('change', updateMsgVisibility);
}
/**
* Show/Hide #jsa based on checkboxes status
*/
function updateMsgVisibility(){
let jj1 = document.getElementById('jj1_ikk');
let jj2 = document.getElementById('jj2_ikk');
if ( (jj1 && (jj1.checked)) || (jj2 && (jj2.checked)) ) {
document.getElementById('jsa').style.display="block";
} else {
document.getElementById('jsa').style.display="none";
}
}
<input type="checkbox" id="jj1_ikk" name="jj1_ikk" /><label for="jj1_ikk">A</label>
<input type="checkbox" id="jj2_ikk" name="jj2_ikk" /><label for="jj2_ikk">B</label>
<div id="jsa" style="display:none;">This is the element that will be shown if both checkboxes aren't checked</div>

JavaScript Checkbox

I am having troubles with a script with JS, I am still learning but I am stuck for a while.
The solution should be,
IF a checkbox is checked and the value is "" <-- the msgbox should say an message that the textbox should be filled with a value, and so for each checked checkbox, if you uncheck the checkbox, it should dissapear.
Code of 2 checkboxes in html page
<label>
bangkirai
<input id="chk_bangkirai" type="checkbox" onchange="enableTextBox()" />
</label>
<input type="text" id="bangkirai" name="bangkirai" disabled onchange="enableTextBox()" />
<label>
beukenhout
<input id="chk_beukenhout" type="checkbox" />
</label>
<input type="text" id="beukenhout" name="beukenhout" disabled/>
and the JavaScript, I made for each checkbox an other function, but I need to combine the error message in the same msgbox.
function enableTextBox() {
divOutput = document.getElementById("msgbox2");
strValideer = "<ul>";
if (document.getElementById("chk_bangkirai").checked === true) {
document.getElementById("bangkirai").disabled = false;
}
else {
document.getElementById("bangkirai").disabled = true;
}
if (document.getElementById("bangkirai").value === "") {
strValideer += "<li><b>bangkirai: </b>verplicht veld</li>";
}
strValideer += "</ul>";
divOutput.innerHTML = strValideer;
}
function enableTextBox2() {
divOutput = document.getElementById("msgbox2");
strValideer = "<ul>";
if (document.getElementById("chk_beukenhout").checked === true) {
document.getElementById("beukenhout").disabled = false;
}
else {
document.getElementById("beukenhout").disabled = true;
}
if (document.getElementById("beukenhout").value === "") {
strValideer += "<li><b>beukenhout: </b>verplicht veld</li>";
}
strValideer += "</ul>";
divOutput.innerHTML = strValideer;
}
I should probably use an array or an for each itteration ... but I can only find examples with forms ...
I will keep looking for a solution myself, but I hope I can get some inspiration here by experienced coders.
Thanks in advance
You could simplify this a lot and make it more... Concise and less dependent on which checkbox you have. We will do this with an external script and no onClick attributes on our HTML. This will enable us to separate our logic code from our design code. I will also use a placeholder instead of value, as it will create issues when people need to start entering a value (aka, you need to only have the text there when theres no value etc...) It just makes it more complicated.
Since we are dealing with numbers ('stuks' or amounts), lets also only allow number values to be inserted. Lastly, I have not bothered to replicate your HTML as I think the simplified example will make it easier to understand. Update I have also added the required and disabled sattributes here, settings your input to required when the checkbox is checked and disabled when not.
Check the below snippet for comments on the steps taken to do this:
// First, let select all fieldsets like this:
var fieldsets = document.querySelectorAll( 'fieldset.checkbox-message' );
// Lets loop through them
for( let i = 0; i < fieldsets.length; i++ ){
// Lets create variables to store our fieldset, checkbox and input for later use.
let fieldset = fieldsets[ i ];
let checkbox = fieldset.querySelector( 'input[type="checkbox"]' );
let input = fieldset.querySelector( 'input[type="number"]' );
// Lets also store the message we put in placeholder
// We will also give it a default value,
// in case you forget to set the placeholder.
let message = input.placeholder || 'Please fill in the amount';
// Now lets define a function that will fill the placeholder
// based on the checked value of the checkbox
// We will be storing it in a variable because of the scope of a `for` block.
// If you would use function setState() it might be defined globally
// So multiply checkboxes would not work.
let setState = function(){
if( checkbox.checked ){
input.placeholder = message;
input.disabled = false;
input.required = true;
} else {
input.placeholder = '';
input.disabled = true;
input.required = false;
}
}
// Now lets listen for changes to the checkbox and call our setState
checkbox.addEventListener( 'change', setState );
// Lrts also call setState once to initialise the correct placeholder
// for our input element to get started. This will remove any placeholders
// if the checkboxes are unchecked.
setState();
}
<fieldset class="checkbox-message">
<label for="bangkirai">Bangkirai</label>
<input type="checkbox" id="bangkirai" />
<input type="number" placeholder="Tell us, how many 'bangkirai'?" />
<span>stuks</span>
</fieldset>
<fieldset class="checkbox-message">
<label for="beukenhout">Beukenhout</label>
<input type="checkbox" id="beukenhout" />
<input type="number" placeholder="How many 'beukenhout'?" />
<span>stuks</span>
</fieldset>
Good luck coding!
#somethinghere's answer is concise but if we modify your answer as it is you could check this
function enableTextBox() {
bangkirai_validation = document.getElementById("bangkirai_validation");
if (document.getElementById("chk_bangkirai").checked === true) {
document.getElementById("bangkirai").disabled = false;
}
else {
document.getElementById("bangkirai").disabled = true;
bangkirai_validation.style.display='none';
return;
}
if (document.getElementById("bangkirai").value =="") {
bangkirai_validation.style.display='block';
}else
{
bangkirai_validation.style.display='none';
}
}
function enableTextBox2() {
beukenhout_validation = document.getElementById("beukenhout_validation");
if (document.getElementById("chk_beukenhout").checked === true) {
document.getElementById("beukenhout").disabled = false;
}
else {
document.getElementById("beukenhout").disabled = true;
beukenhout_validation.style.display='none';
return;
}
if (document.getElementById("beukenhout").value == "") {
beukenhout_validation.style.display='block';
}else
{
beukenhout_validation.style.display='none';
}
}
<fieldset>
<legend>Bestel gegevens</legend>
<div class="container">
<div class="row">
<div class="span7 id=" houtsoorten"">
<div class="control-group">
<label class="control-label">
bangkirai
<input id="chk_bangkirai" type="checkbox"
onchange="enableTextBox()" >
</label>
<div class="controls">
<div class="input-append">
<input class="inpbox input-mini"
type="number" id="bangkirai" name="bangkirai" placeholder="aantal" disabled
onkeyup="enableTextBox()" onchange="enableTextBox()">
<span class="add-on">stuks</span>
<div style="display:none;" id="bangkirai_validation">Please enter a value</div>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">
beukenhout
<input id="chk_beukenhout" type="checkbox" onchange="enableTextBox2()" >
</label>
<div class="controls">
<div class="input-append">
<input class="inpbox input-mini"
type="number" id="beukenhout" name="beukenhout" placeholder="aantal"
disabled onkeyup="enableTextBox2()" onchange="enableTextBox2()" >
<span class="add-on">stuks</span>
<div style="display:none;" id="beukenhout_validation">Please enter a value</div>
</div>
</div>
</div>

Enable button if radio button selected

I've tried almost all the methods mentioned here and in other websites but still I'm stuck so that's why I'm asking it here.
I've created a form (with out <form></form> tags) in this form I'm creating 4 radios buttons using a while loop data is being pulled from a database.
To send data I'm using a JavaScript(Ajax) which is bound to a button click event.
Now I want to keep the submit button disabled until all the filed's are filled the last filed's are the radio buttons I'm tried to use many other ways to do this but nothing happened so any way below is code I'm using.
function checkUrole() {
var roles = document.getElementById("userRoles"),
btn = document.getElementById("submit"),
len = roles.length,
sel = null;
for(var i=0; i < len; i++){
if (roles.checked){
sel = roles[i].value;
}
}
if (sel === null){
document.getElementById("msgID").innerHTML = "9";
btn.disabled = true;
}else{
btn.disabled = false;
}
}
And this is my HTML
<label for="userRoles">User Role:</label><br>
<?php while ($row = $getUserRoleQuery -> fetch(PDO::FETCH_ASSOC)) { ?>
<input type="radio" id="userRoles" name="userRoles" value="<?php echo $row["urId"]; ?>" onmousedown="checkUrole()"><?php echo $row["userRole"]; }?>
<label id="msgID" hidden></label>
<div id="msg"></div>
Basically the HTML will create something like this,
<input type="radio" id="userRoles" name="userRoles" value="1" onmousedown="checkUrole()">Admin
<input type="radio" id="userRoles" name="userRoles" value="2" onmousedown="checkUrole()">Manager
<input type="radio" id="userRoles" name="userRoles" value="3" onmousedown="checkUrole()">Team Leader
<input type="radio" id="userRoles" name="userRoles" value="4" onmousedown="checkUrole()">User
I don't like write a code like this,
if(document.getElementById("userRoles1").checked{
something here;
}else if(document.getElementById("userRoles2").checked{
something here;
}else{
something here;
}
above I think makes the program a bit less dynamic 'cos if a new user role is added I've add a new IF to the loop.
So is there any way I solve this and I like to use JavaScript if can.
UPDATE: Thanks to #zer00ne I solved this problem and below is the finale working code hope this helps any one in the future as well.
My HTML:
<script language="JavaScript" type="text/javascript" src="../jScripts/userCreatFunctions.js">
<div id="userRoles">
<input type="radio" name="userRoles" value="1" checked>Admin
<input type="radio" name="userRoles" value="2">Manager
<input type="radio" name="userRoles" value="3">Team Leader
<input type="radio" name="userRoles" value="4">User
</div>
My JaveScript:
$(document).ready(function () {
/*Register the change element to #roles
|| When clicked...*/
//This code base was originally developed by zer00ne I'm using it under his permission
//Thanks man.
var form = document.getElementById('userRoles');
if (form){
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Reference the submit button
var btn = document.querySelector('[name=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
}
function roleDist(rank) {
var display = document.getElementById("msg");
if (rank !== null) {
display.innerHTML = "All done! You can save";
} else {
display.innerHTML = "Please Select User Type";
}
}
});
Use the $(document).ready(function () {}) other wise the script get loaded before the DOM which leads to a NULL value making the script none functional.
Firstly, you don't need the id's on every input element. You can get an array of the button element by name using getElementsByName, here is an example of how you would do "something" based on one of those being checked:
JS (Using ES6)
const getRadioValue = (name) => {
const radios = document.getElementsByName(name);
let val;
Object.keys(radios).forEach((obj, i) => {
if (radios[i].checked) {
val = radios[i].value;
}
});
return val;
}
document.getElementById('form').addEventListener('change', (e) => {
getRadioValue('userRoles'); // value of checked radio button.
});
HTML
<div id="form">
<input type="radio" name="userRoles" value="1">Admin
<input type="radio" name="userRoles" value="2">Manager
<input type="radio" name="userRoles" value="3">Team Leader
<input type="radio" name="userRoles" value="4">User
</div>
JsFiddle Example
UPDATE - improved
A more efficient method would be using the Array.prototype.find() method, this is better because:
The find method executes the callback function once for each index of the array until it finds one where callback returns a true value. If such an element is found, find immediately returns the value of that element.
In other words, it doesn't need to iterate the entire Array, once we find what we want it returns.
Note: Use the below snippets within the change event mentioned above to retrieve the checked value.
JS (Using ES6)
const getCheckedRadioValue = (name) => {
const radios = document.getElementsByName(name);
try {
// calling .value without a "checked" property will throw an exception.
return Array.from(radios).find((r, i) => radios[i].checked).value
} catch(e) { }
}
getCheckedRadioValue('userRoles');
JsFiddle Example
JS (Without ES6)
function getCheckedRadioValue(name) {
var radios = document.getElementsByName(name);
var val;
for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
return val; // return value of checked radio or undefined if none checked
}
getCheckedRadioValue('userRoles');
JsFiddle Example
References
Array.prototype.forEach()
Array.from()
Array.prototype.find()
Not exactly sure what you are trying to do, so here is what I'm guessing:
Need to determine the value of a checked radio input
Need to enable a submit button that's determined by a checked radio
Need to effectively call upon other functions, run additional interactions, etc. depending on what was specifically checked.
Details are commented in Snippet
SNIPPET
// Reference #roles
var form = document.getElementById('roles');
/* Register the change element to #roles
|| When clicked...
*/
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Find the textNode next to target
var label = target.nextSibling;
// Reference the #display
var display = document.getElementById('display');
// Display the <label>s text and radio value
display.value = label.textContent + ' - Rank: ' + target.value;
// Reference the submit button
var btn = document.querySelector('[type=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
function roleDist(rank) {
switch (rank) {
case '4':
alert('Rank 4 - Limited Access');
// Take user to landing page
break;
case '3':
alert('Rank 3 - Basic Access');
// Take user to dashboard
break;
case '2':
alert('Rank 2 - Advanced Access');
// Take user to database
break;
case '1':
alert('Rank 1 - Full Access');
// Take user to admin panel
break;
}
}
input,
output,
[type=submit] {
font: inherit;
cursor: pointer;
}
[type=submit] {
float: right;
}
<form id='roles'>
<input type="radio" name="role" value="1">Admin
<input type="radio" name="role" value="2">Manager
<input type="radio" name="role" value="3">Team Leader
<input type="radio" name="role" value="4">User
</form>
<br/>
<label for='display'>Role: </label>
<!--
Since #display and submit button are outside of
the <form>, using the form attribute and the
<form>'s #id as the value establishes an
association between them and <form>
-->
<output id='display' form='roles'></output>
<br/>
<input type='submit' form='roles' disabled>
There is very basic mistake in your markup you should not use elements with same id's in
You can use class instead of id (give class to radioboxes)
document.getElementsByClassName("userRoles")
<input type="radio" class="userRoles" name="userRoles" value="1" onmousedown="checkUrole()">Admin
Rest of your code seems ok

IF ELSE statement with && and || condition

I have a group of checkboxes (id = "first" id = "second") and the main checkbox (id = "main").
<input type='checkbox' id="main_button" onclick="Indeterminate()"><label for="main_button">Main checkbox of group</label>
<input type='checkbox' id="first" onclick="Indeterminate()"><label for="first">First thing</label>
<input type='checkbox' id="second" onclick="Indeterminate()"><label for="second">Second thing</label>
If one or more of the group checkbox checked then the main have indeterminate condition. If all checked then the main checkbox have also checked condition.
function Indeterminate() {
if (document.getElementById('first').checked || document.getElementById('second').checked) {
document.getElementById('main_button').indeterminate = true;
} else if (document.getElementById('first').checked && document.getElementById('second').checked) {
document.getElementById('main_button').checked;
} else {
document.getElementById('main_button').indeterminate = false;
}
}
In my IF ELSE statement, conditions IF and ELSE works, but there is something wrong with ELSE IF. Probably doing a simple mistake or? Thank you!
JSFiddle example
var main = document.getElementById('main_button');
var first = document.getElementById('first');
var second = document.getElementById('second');
function Indeterminate() {
if (first.checked && second.checked) {
main.checked = true;
main.indeterminate = false;
} else if (first.checked || second.checked)
main.indeterminate = true;
else
main.indeterminate = false;
}
<input type='checkbox' id="main_button" onclick="Indeterminate()">
<label for="main_button">Main checkbox of group</label>
<input type='checkbox' id="first" onclick="Indeterminate()">
<label for="first">First thing</label>
<input type='checkbox' id="second" onclick="Indeterminate()">
<label for="second">Second thing</label>
Your && code is right, but it's the && situation is apart of you || code, so When || is not true, the && will not true too. Just change their sequence.
I think the problem is that you are getting the meaning of || wrong. It means or in the sense that either the left or the right expression is true - or both!
Therefore, your else if will never be called, because if a.checked && b.checked is true, then a.checked || b.checked will always be true as well, and the if will be executed before the else if is even checked.
Therefore, the correct solution is:
function Indeterminate() {
if (document.getElementById('first').checked && document.getElementById('second').checked) {
document.getElementById('main_button').checked;
} else if (document.getElementById('first').checked || document.getElementById('second').checked) {
document.getElementById('main_button').indeterminate = true;
} else {
document.getElementById('main_button').indeterminate = false;
}
}
Here, you first check for the more specific condition a.checked && b.checked. Only if that condition is not true, the weaker condition a.checked || b.checked is evaluated.
As commented before, you should move && before ||.
Reason for this is if first is selected or both is selected, first.checked || second.checked will always be true. Only situation when || will fail is when both are unchecked, and then && will also fail.
JSFiddle
Updated Code
function Indeterminate() {
var first = document.getElementById('first').checked;
var second = document.getElementById('second').checked
var main = document.getElementById('main_button');
if (first && second) {
main.indeterminate = false;
main.checked = true
} else {
main.checked = main.indeterminate = first || second
}
}
<input type='checkbox' id="main_button" onclick="Indeterminate()">
<label for="main_button">Main checkbox of group</label>
<br>
<input type='checkbox' id="first" onclick="Indeterminate()">
<label for="first">First thing</label>
<br>
<input type='checkbox' id="second" onclick="Indeterminate()">
<label for="second">Second thing</label>
As commented by Bekim Bacaj, I have updated my code. JSFiddle

Check All checkboxes not pushing names into array

I have a form with checkboxes. The javascript function allPosPlayersCheckboxes utilizes a "Check All" Checkbox that controls the others. The other functions (getPosAllFilterOptions & getPosPlayersFilterOptions) push the "name" properties into an array. This all is triggered when anything is changed on the form.
Suppose that all checkboxes are unchecked. If the user checks the "nonP_all" checkbox, it will automatically check the other checkboxes with class="nonP". Unfortunately, when the "name" properties are pushed into the array, it will not include any with class="nonP".
I"m unsure why they are not included in the array. Are the functions (getPosAllFilterOptions & getPosPlayersFilterOptions) not waiting for allPosPlayersCheckboxes to complete? Is there a way to have the secondary checkboxes included in the arrays? Thanks for any help!
<form id="formFilter">
<h2>Filter options</h2>
<div>
<input type="checkbox" id="nonP_all" class="Pos_all" name="nonP" checked="checked">
<label for="nonP">Position Players</label>
<input type="checkbox" id="C" class="nonP" checked="checked" name="C">
<label for="C">C</label>
<input type="checkbox" id="1B" class="nonP" checked="checked" name="1B">
<label for="1B">1B</label>
<input type="checkbox" id="2B" class="nonP" checked="checked" name="2B">
<label for="2B">2B</label>
<input type="checkbox" id="3B" class="nonP" checked="checked" name="3B">
<label for="3B">3B</label>
<input type="checkbox" id="SS" class="nonP" checked="checked" name="SS">
<label for="SS">SS</label>
<input type="checkbox" id="LF" class="nonP" checked="checked" name="LF">
<label for="LF">LF</label>
<input type="checkbox" id="CF" class="nonP" checked="checked" name="CF">
<label for="CF">CF</label>
<input type="checkbox" id="RF" class="nonP" checked="checked" name="RF">
<label for="RF">RF</label>
<input type="checkbox" id="DH" class="nonP" checked="checked" name="DH">
<label for="DH">DH</label>
</div>
function allPosPlayersCheckboxes(){
$("#nonP_all").click(function(){ // When it is clicked....
$('.nonP').prop('checked', this.checked); // Sets all to reflect "All"
});
$(".nonP").click(function(){ // When any are clicked....
if($(".nonP").length == $(".nonP:checked").length){ // If all are checked...
$("#nonP_all").prop("checked", true); // Sets "All" to "checked"
}else{
$("#nonP_all").prop("checked", false); // Sets "All" to "unchecked"
}
});
};
function getPosAllFilterOptions(){
var pos_all_opts = new Array();
$(".Pos_all:checked").each(function(){
pos_all_opts.push($(this).attr('name')); // places names into array
});
return pos_all_opts;
}
function getPosPlayersFilterOptions(){
var nonP_opts = new Array();
$(".nonP:checked").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
return nonP_opts;
}
var $formFilter = $("#formFilter");
$formFilter.change(function(){
allPosPlayersCheckboxes();
var pos_all_opts = getPosAllFilterOptions();
var nonP_opts = getPosPlayersFilterOptions();
console.log("pos_all_opts = " + pos_all_opts);
console.log("nonP_opts = " + nonP_opts);
updateQuery(pos_all_opts, nonP_opts);
});
updateQuery();
The reason that you are having an issue is because the checking of the boxes event is being caught at the form change event handler, and the code that checks and unchecks all of the other boxes hasn't executed yet. As a result when you call your functions, the count for checked boxes is 0. This also happens when you uncheck one of the position checkboxes, eventually the pos_all_opts variable gets out of sync and is incorrect as well.
These click handlers don't need to be in a function. They are handlers that are hooked into the behavior of your checkboxes.
$("#nonP_all").click(function(){ // When it is clicked....
$('.nonP').prop('checked', this.checked); // Sets all to reflect "All"
});
$(".nonP").click(function(){ // When any are clicked....
if($(".nonP").length == $(".nonP:checked").length){ // If all are checked...
$("#nonP_all").prop("checked", true); // Sets "All" to "checked"
}else{
$("#nonP_all").prop("checked", false); // Sets "All" to "unchecked"
}
});
This is probably a little less than ideal, but it works. The code that was in the functions to build the arrays has been moved into the change handler for the form.
$("#formFilter").change(function(event){
var pos_all_opts = [];
var nonP_opts = [];
if(event.target === $("#nonP_all")[0] && event.target.checked) {
pos_all_opts = 'nonP';
$(".nonP").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
} else if(event.target === $("#nonP_all")[0] && !event.target.checked) {
pos_all_opts = [];
nonP_opts = [];
} else if(event.target !== $("#nonP_all")[0] && $(".nonP:checked").length === 9) {
pos_all_opts = 'nonP';
$(".nonP").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
} else {
pos_all_opts = [];
$(".nonP:checked").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
}
console.log("pos_all_opts = " + pos_all_opts);
console.log("nonP_opts = " + nonP_opts);
updateQuery(pos_all_opts, nonP_opts);
});
updateQuery();
Fiddle for reference

Categories