How to keep a stored array of input checkbox value? - javascript

I have a input checkbox that act as a category filter. I want to store only those values of input checkboxes in an array that are checked in a var checkedAttr. Then do a test if any of the already existing values match any in the array and if it does delete it. The problem I'm having is that... when an input checkbox is clicked, it will store it as many times as the $each loop goes or input checkboxes there are, in this case (three times). I also noticed when unchecking more than one, then rechecking the same one, it will add the values as many times as the $each loop goes and will somehow bypass deleting from the array. I just want to simply add (checked values) / delete (unchecked values) from the array every time the user checks or unchecks.
Here's a jsfiddle.
HTML:
<div id="category-list">
<h1>Categories</h1>
<input class="categories" type="checkbox" name="filter" value="Math" checked>Math<br/>
<input class="categories" type="checkbox" name="filter" value="Science" checked>Science<br/>
<input class="categories" type="checkbox" name="filter" value="Reading" checked>Reading
</div>
jQuery:
var checkedAttr = []; // array for checked attributes
// change event listener for whenever one or more of the following checkboxes have been checked/unchecked
$('#category-list :checkbox').change(function()
{
var value = $(this).val();
if($(this).is(':checked')) // checked
{
console.log(value + ' is now checked!!!!!!!!!!!!!!!!!!!!!!!!');
$('#category-list :checkbox').each(function(i, item){ // loop thru the input checkboxes
if(!(value === $(item).val())) // check if the current value does NOT match that already stored in array
{
checkedAttr.push(value); // add value to array
console.log("checkedAttr:", checkedAttr);
}
else // if it does match...
{
checkedAttr.splice(i, 1);// remove it from array
console.log("checkedAttr:", checkedAttr);
}
});
// check which attributes are checked and store in 'checkedAttr' array
//$('input[name=filter]').each(function(i, item){
//});
}
else // unchecked
{
console.log(value + ' is now unchecked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
});

Check it Brother its working as you want
var checkedAttr = [];
$('#category-list :checkbox').change(function()
{
checkedAttr = [];
$('#category-list :checkbox').each(function(i, item){
if($(item).is(':checked'))
{
checkedAttr.push($(item).val());
}
});
console.log("checkedAttr:", checkedAttr);
});
You can also check it in JSFiddle
https://jsfiddle.net/xdrLra77/

You can do it simply with a mapcall
var checkedAttr = [];
$('#category-list :checkbox').change(function() {
checkedAttr = $('#category-list :checked').map(function(){
return $(this).val();
}).get();
console.log(checkedAttr);
});
(Updated jFiddle)
(Edit: better yet, put the condition in the jQuery selector)

Edited
var checkedAttr = []; // array for checked attributes
//first load, see what is checked
$('#category-list :checkbox').each(function(){
if($(this).is(':checked')) // checked
checkedAttr.push($(this).val())
})
// change event listener for whenever one or more of the following checkboxes have been checked/unchecked
$('#category-list :checkbox').change(function()
{
var value = $(this).val();
var position = checkedAttr.indexOf($(this).val());
if($(this).is(':checked')) // checked
{
if(position == -1){ // dnot exist in array, add
checkedAttr.push($(this).val());
console.log("checkedAttr:", checkedAttr);
}else{ // exist in array, do nothing
//do nothing
}
console.log(value + ' is now checked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
else // unchecked
{
if(position == -1){ // dont exist in array, do nothing
//do nothing
}else{ // exist in array, remove
checkedAttr.splice(position,1);
console.log("checkedAttr:", checkedAttr);
}
console.log(value + ' is now unchecked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
});

You can get the checked elements by using $('.categories:checked'). Then you may iterate through those values to get the actual values
var checkedValues= $('.categories:checked');
var valuesArray=[];
$.each(checkedValues, function(checkedValue){
valuesArray.push(checkedValue.value)
}

Use $.inArray:
if (index === -1 && $(this).is(':checked')) {
checkedAttr.push(value); // add value to array
console.log("added:", checkedAttr);
} else if (index !== -1 && ! $(this).is(':checked')) {
checkedAttr.splice(index, 1);// remove it from array
console.log("removed:", checkedAttr);
}
Amended fiddle: https://jsfiddle.net/o1rmz1o1/4/

Related

Jquery make checkbox checked on other checkbox removal

I'm trying to make a filter to output some filtered results. The output goes to an array. I have four checkboxes. I was almost able to achieve the result I wanted. However, I want to make the All Levels checkbox checked again when there is no selections left. Here is what I have at the moment. I'm new to jquery so my code must be not efficient. If one can suggest or improve my code to achieve exact same result that would be great too! Thanks!
HTML
<div id="course-levels" class="list-group">
<input type="checkbox" value="all-levels" id="all-levels">
<input type="checkbox" value="degree" class="group">
<input type="checkbox" value="pgd" class="group">
<input type="checkbox" value="hnd" class="group">
</div>
Jquery
<script>
$(document).ready(function(){
// get reference to input elements
var inp = document.getElementsByTagName('input');
var levels = [];
// if checkboxes under 'group' class is not checked
if ($('input.group').prop('checked') == false) {
// make #all-levels default selected checkbox
$('#all-levels').prop('checked', true);
// make it readonly
$("#all-levels").attr('disabled', true);
// get other input values to levels array
for (var i=0; i < inp.length; i++) {
// skip default checkbox value
if (inp[i].value == 'all-levels') {
continue;
}
levels.push(inp[i].value);
}
console.log(levels);
}
// if user checked any other checkbox now
$('input.group').on('click', function () {
// remove check from default checkbox
$('#all-levels').prop('checked', false);
// make it enabled
$('#all-levels').removeAttr('disabled');
// get new values to levels array
levels = $('#course-levels input:checked').not($('#all-levels')).map(function () {
return this.value;
}).get();
console.log(levels);
}).eq(0).change();
// if all levels checkbox is clicked again
$('#all-levels').on('click', function(){
$('input.group').prop('checked', false);
// make default checkbox readonly so it will stay default
$('#all-levels').attr('disabled', true);
// make array empty
levels = [];
// get all input values to levels array
for (var i=0; i < inp.length; i++) {
// skip default checkbox value
if (inp[i].value == 'all-levels') {
continue;
}
levels.push(inp[i].value);
}
console.log(levels);
});
});
</script>
You can do this simply by checking if all the .group checkbox length is same as checked .group checkbox length or not and based on that make #all-levels selected again like:
$('#all-levels').prop('checked', $('input.group').length === $('input.group:checked').length);
$(document).ready(function() {
// get reference to input elements
var inp = document.getElementsByTagName('input');
var levels = [];
// if checkboxes under 'group' class is not checked
if ($('input.group').prop('checked') == false) {
// make #all-levels default selected checkbox
$('#all-levels').prop('checked', true);
// make it readonly
$("#all-levels").attr('disabled', true);
// get other input values to levels array
for (var i = 0; i < inp.length; i++) {
// skip default checkbox value
if (inp[i].value == 'all-levels') {
continue;
}
levels.push(inp[i].value);
}
console.log(levels);
}
// if user checked any other checkbox now
$('input.group').on('click', function() {
// remove check from default checkbox
$('#all-levels').prop('checked', false);
// make it enabled
$('#all-levels').removeAttr('disabled');
// get new values to levels array
levels = $('#course-levels input:checked').not($('#all-levels')).map(function() {
return this.value;
}).get();
//console.log(levels);
$('#all-levels').prop('checked', $('input.group').length === $('input.group:checked').length);
}).eq(0).change();
// if all levels checkbox is clicked again
$('#all-levels').on('click', function() {
$('input.group').prop('checked', false);
// make default checkbox readonly so it will stay default
$('#all-levels').attr('disabled', true);
// make array empty
levels = [];
// get all input values to levels array
for (var i = 0; i < inp.length; i++) {
// skip default checkbox value
if (inp[i].value == 'all-levels') {
continue;
}
levels.push(inp[i].value);
}
console.log(levels);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="course-levels" class="list-group">
<input type="checkbox" value="all-levels" id="all-levels">
<input type="checkbox" value="degree" class="group">
<input type="checkbox" value="pgd" class="group">
<input type="checkbox" value="hnd" class="group">
</div>

Get checkbox state in array with javascript or jquery

I have on a devexpress grid one column with a checkbox. It is a simple checkbox column, which depends on which checkbox is checked I need to invoke different methods, it is not bind to a property from model.
I need to know which row is selected. I have tried to resolve this with this javascript code:
if (document.getElementById('selectDamage').checked) {
alert("checked");
var checkedValues = $('input:checkbox:checked').map(function () {
return this.value;
}).get();
console.log(checkedValues);
} else {
alert("You didn't check it! Let me check it for you.");
}
This returns only the checked values. I need to return something like Array{on, off, on}, the first is checked, the second one is unchecked and the last is checked. Is there a way in javascript or jquery to do that?
first add checkbox in grid then take a button and set onclick function of this button , then all checked data will go through array and finally split the array value and do your further job.(array value are saved into hidden field, i used hidden field and set the id lblarr )
<dx:GridViewDataColumn >
<HeaderTemplate>
</HeaderTemplate>
<DataItemTemplate>
<input type="checkbox" class="case" id="chkchild" name="checkboxModel" value='<%#Eval("SALE_DOC_#") %>' />
</DataItemTemplate>
</dx:GridViewDataColumn>
<script>
$('#btn1').click(function () {
var CheckCount =$('input:checkbox[name="checkboxModel"]:checked').length;
if (CheckCount > 0)
{
var valuesArray =
$('input:checkbox[name="checkboxModel"]:checked').map(function () {
return this.value;
}).get().join(",");
$('#<%=lblarr.ClientID%>').val(valuesArray);
}
else {
alert('Please check at least one data!')
}
})
</script>
Depending on the layout of your html, you could do something like this to get an updated array of indexed checked states
var els = $("table#gvDamages3_DXMainTable input[type=checkbox]");
els.on("change", function(){
var vals = [];
els.each(function() {
vals.push(this.checked);
});
console.log(vals);
});

jQuery get checked checkboxes from name[]

I have checkboxes like so:
<ul id="searchFilter">
<li><input type="checkbox" name="price[]" class="cb_price" value="1"> $200,000 to $299,999</li>
<li><input type="checkbox" name="price[]" class="cb_price" value="3"> $300,000 to $399,999</li>
<li><input type="checkbox" name="price[]" class="cb_price" value="5"> $400,000 to $499,999</li>
<li><input type="checkbox" name="price[]" class="cb_price" value="8"> $500,000+</li>
</ul>
How would I alert the price[] to see what is checked? I am very new at jquery :(
First, you can get the checkboxes by name:
var checkboxes = $('input[name="price[]"]');
Then, to get the values of the checked ones, you can filter by the pseudo selector :checked, and then collect their values:
checkboxes.filter(":checked").map(function () {
return this.value;
}).get()
DEMO: http://jsfiddle.net/Fn9WV/
References:
jQuery().filter() - http://api.jquery.com/filter/
jQuery().map() - http://api.jquery.com/map/
You can try this:-
var selected = [];
$('[name="price[]"]:checked').each(function(checkbox) {
selected.push(checkbox);
});
Use the selector $('#searchFilter [name="price[]"]:checked') with jquery to find all the checked checkboxes with the name "price[]" in this form. This will be zero or more elements, depending on how many are checked.
Then use the jquery each() function to iterate over the found checkbox elements, and collect their values into the "checked" array. In the callback function to each(), the this points to the current element's dom node, wrap it with $(this) to create a jquery object and use .val() to retrieve the value from it.
Finally merge the items into a string, to form a comma separated list using the join() function of the "checked" array. It can be an empty string if none of the checkboxes are checked.
var checked = [];
$('#searchFilter [name="price[]"]:checked').each (function (i, e)
{
checked.push ($(this).val ());
});
alert (checked.join (','));
Notice that other answers used this.value to retrieve the "value" attribute of the checkbox instead of using $(this).val(), which is the jquery way to do it and less error prone.
Try the following:
var alert="";
$('input[type=checkbox]').each(function () {
if($(this).attr("checked") == 1)) alert += $(this).val();
if(alert.length > 1) alert(alert);
});
One way would be to set each checkbox to a specific id. Then you could use $('#' + id).is(":checked") to see if the checkbox is checked. If the checkbox is checked, you could get the range and store it in a variable. You can then return that variable.
Check this page if you need some help with the checkbox.
//get val on click
$(document).on('click', ".cb_price", function () {
if ($(this).is(':checked')) {
alert($(this).val());
}
});
//a button to call the function
$(document).on('click', ".some_button", function () {
function getitems();
});
function getitems(){
$(".cb_price").each(function () {
//
var $chk = $(this);
if ($chk.is(':checked')) {
checkboxes = checkboxes + $(this).val() + ","
}
});
alert(checkboxes);
}

Client-side searching in checkbox value

I need help.. for now I'm trying to create a client search but I don't know how to compare values from input text to checkboxes.
jsFiddle Example
Example:
jQuery("#searchBox").on("keyup paste", function() {
var value = jQuery(this).val().toUpperCase();
var rows = jQuery(".sp_country");
rows.hide();
if(value === '') {
rows.show();
return false;
}
//need something here to compare values on checkboxes and show does checkedbox who match
});
Here is my check box located
<span class="sp_country">
<input class="cp_country" style="cursor:pointer; display:none;" type="checkbox" name="country" value="Afghanistan"> Afghanistan
</span>
You can use .filter() method:
rows.filter(function() {
return $(this).text().toUpperCase().indexOf(value) > -1;
}).show();
Or in case that you want to compare the input with value of checkboxes:
rows.filter(function(){
return this.children[0].value.toUpperCase().indexOf(value) > -1;
}).show();
You can can also use the jQuery's .find() method for selecting the input descendants.
Try this
$("cp_country").each(function(){
if($(this).val()==("#searchBox").val()){
$(this).parent(".sp_country").show();
}
});
Whole idea is:
iterate through each of the checkbox value
if the value matches with search box value then
show the parent span element
Try this:
$("#searchBox").on("keyup paste", function() {
var value = $(this).val().toUpperCase();
var rows = $(".cp_country");
rows.hide();
if(value === '') {
rows.show();
return false;
}
else{
rows.each(function(){
if($(this).val().toUpperCase().indexOf(value) != -1){
$(this).show();
}
else{ $(this).hide();}
});
}
});

How to hide the parent of an unchecked checkbox?

I have a set of random/dynamic generated div checkboxes:
<div>A1 <input type='checkbox' name='A[]' value='A1'> </div>
<div>A2 <input type='checkbox' name='A[]' value='A2'> </div>
<div>A3 <input type='checkbox' name='A[]' value='A3'> </div>
<div>B1 <input type='checkbox' name='B[]' value='B1'> </div>
<div>B2 <input type='checkbox' name='B[]' value='B2'> </div>
<div>C1 <input type='checkbox' name='C[]' value='C1'> </div>
What I am trying to do is when the user:
checks any A then the others will hide (entire div) but all A will still show.
unchecks a checkbox, then all A, B, C will show again.
This is because I am preventing the user from checking a mix of options.
PS:
You can provide a solution that might need me to modify the generated output of checkboxes.
try this fiddle
$("input[type=checkbox]").on("change", function() {
var thisName = $(this).attr("name");
if($(this).is(':checked')){
$(':checkbox').parent().hide();
$('input:checkbox[name|="'+thisName+'"]').parent().show();
} else {
$(':checkbox').parent().show();
}
});​
Try this one,
$('input:checkbox').click(function(){
if($(this).attr('checked') == 'checked'){
$('input:checkbox').parent('div').hide();
$('input:checkbox[name="'+$(this).attr('name')+'"]').parent('div').show();
}else{
if(!$('input:checkbox[checked="checked"]').length){
$('input:checkbox').parent('div').show();
}
}
})
​
Demo: http://jsfiddle.net/muthkum/uRd3e/3/
You can use some JQuery traversing to hide the non-matching elements:
// add the event handler
$("input[type=checkbox]").on("change", function() {
// get whether checked or unchecked
var checked = $(this).prop("checked") === true;
// get the name of the clicked element (eg, "A[]")
var thisName = $(this).prop("name");
// get the name of the clicked element (eg, "A[]")
var thisName = $(this).prop("name");
// get the grandparent element
$(this).parent().parent()
// get all the checkboxes
.find("input[type=checkbox]")
// filter to only the ones that don't match the current name
.filter(function(i, e) { return e.name != thisName; })
// hide or display them
.css("display", checked ? "none" : "");
});
you can simple do it like this
$('input[type=checkbox]').change(function () {
if ($(this).attr('checked')) {
var Name = $(this).prop("name");
$('div').filter(function(){
return $(this).find('input[type=checkbox]').prop("name") != Name;
}).hide();
}
else
{
$('input[type=checkbox]').attr('checked',false);
$('input[type=checkbox]').parent('div').show();
}
});​
Live Demo
Try code bellow:
$(":checkbox").click(function() {
var identifier = $(this).val().substring(0, 1);
$("input[type='checkbox']").each(function() {
if ($(this).val().indexOf(identifier) != -1) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
if ($("input:checked").length == 0) {
$("input[type='checkbox']").parent().show();
}
});
You can try on jsFiddle
This will hide all other checkbox types when FIRST of a type is checked and show all the other checkbox types when ALL of the checked box type are unchecked:
$("input:checkbox").on("change", function() {
// get the name attribute
var nameAttr = $(this).prop("name");
// check how many checkbox inputs of that name attribute are checked
var checkedLength = $("input:checkbox[name=\"" + nameAttr + "\"]:checked").length;
// if 0, display other checkbox inputs, else if 1 hide all of the rest
if(checkedLength == 0) {
$("input:checkbox[name!=\"" + nameAttr + "\"]").parent().show();
}else if(checkedLength == 1) {
$("input:checkbox[name!=\"" + nameAttr + "\"]").parent().hide();
}
});
Overwhelmed by choice! Here's a plain JS version that just disables members of the non–selected groups.
I think that's better than hiding them so users can see the other options after they've selected one. Otherwise, to see the other options again, they must deselect all checkboxes in the group.
Note that div is a parent of the inputs, the listener passes a reference to the element and the related event object, modify as required.
<script>
function doStuff(div, evt) {
var checked, el, group, j, inputs, name, re;
var t = evt.target || evt.srcElement;
if (t.nodeName && t.nodeName.toLowerCase() == 'input' && t.type == 'checkbox') {
inputs = div.getElementsByTagName('input');
name = t.name;
// Set checked to true if any input with this name is checked
group = document.getElementsByName(name);
j = group.length;
while (j-- && !checked) {
checked = group[j].checked;
}
// Loop over inputs, hide or show depending on tests
for (var i=0, iLen=inputs.length; i<iLen; i++) {
el = inputs[i];
// If name doesn't match, disable
el.disabled = checked? (el.name != name) : false;
}
}
}
</script>
<div onclick="doStuff(this, event)">
<div>A1 <input type='checkbox' name='A[]' value='A1'></div>
<div>A2 <input type='checkbox' name='A[]' value='A2'></div>
<div>A3 <input type='checkbox' name='A[]' value='A3'></div>
<div>B1 <input type='checkbox' name='B[]' value='B1'></div>
<div>B2 <input type='checkbox' name='B[]' value='B2'></div>
<div>C1 <input type='checkbox' name='C[]' value='C1'></div>
</div>
Thanks guys, especially dbaseman (get me ideal) :
ok, Here is my code after referring from you all.
$("input[type=checkbox]").on("click", function() {
var sta = $(this).is(":checked"); sta=(sta==true?1:0);
if(sta==1){
var thisName = $(this).prop("name"); thisName=thisName.replace("[]","");
$("div input[type=checkbox]:not([name^=" + thisName + "])").parent().hide();
}else{
var num = $("[type=checkbox]:checked").length;
if(num==0){
$("div input[type=checkbox]").parent().show();
}
}
});
so far code able is performing as what i need.
Ps: i am still weak on jquery travelling part
Ps: Edited on re-opening all checkboxes part
Thanks once again!

Categories

Resources