I found this answer which does part of what I want to do, uncheck checkboxes when people go past a certain limit.
Now I want to modify it so that the values of the checkboxes are added to and removed from a string as the checkboxes are checked/unchecked.
My updated code looks like this:
var filterURL = '';
var checked = [],
$check = $('.accordion-list input').change(function() {
checked.push(this);
checked = $(checked);
checked.prop('checked', false).slice(-6).prop('checked', true);
if($(this).is(':checked')) {
filterURL += ($(this).val());
}
else {
filterURL = filterURL.replace($(this).val(),'');
}
alert(filterURL);
});
This works fine until I start to try and uncheck checkboxes – they don't uncheck and the value keeps getting appended to the string.
Working demo
$('.checkboxes input').change(function() {
var filterURL = $('.checkboxes input:checked').map(function(){
return $(this).val();
}).get().join('');
$('#output').html(filterURL);
});
var vals = [];
$('input:checkbox:checked').each(function() { vals.push($(this).val()); });
Related
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/
Hi I am developing one jquery application where I have one choosen dropdownlistbox and gridview. The first column of gridview contains checkboxes and at the top it also contains check all button. For example if I check 3 rows inside the gridview then corresponding values in dropdownlistbox i need to disable. I am trying as below.
This is the code to get all the cheked values from gridview.
var checkedValues = [];
$("#<%=gdvRegretletter.ClientID %> tr").each(function () {
if($(this).closest('tr').find('input[type="checkbox"]').prop('checked', true))
{
checkedValues += $(this).val();
}
});
Once i get values in array and when i go to dropdown i have below code.
$('.limitedNumbSelect').change(function (e) {
$("#limitedNumbSelect > option").each(function () {
//if (this.value == checkedValues) If this.value is equal to any value from checkedValues then i want to hide that value inside dropdownlistbox.
// Here i want to hide all values of checkedValues array(values will be same in dropdownlistbox)
});
});
I tried as below.
$('.limitedNumbSelect').change(function (e) {
var checkedValues = [];
$("#<%=gdvRegretletter.ClientID %> tr").each(function () {
if ($(this).closest('tr').find('input[type="checkbox"]').prop('checked', true)) {
checkedValues.push($(this).closest('tr').find('td:eq(2)').text().trim());
}
});
$(".limitedNumbSelect > option").each(function () {
var val = $(this).val();
alert(val);
var display = checkedValues.indexOf(val) === -1;
$(this).toggle(display);
$('.limitedNumbSelect option[value=' + display + ']').hide();
$(".limitedNumbSelect").find('option:contains(' + display + ')').remove().end().chosen();
});
});
In above code there is one bug. For example if i select one value from gridview then if i click on dropdown i am able to select that value(on first click). On second click required value will hide.
Above code does not work. Array checkedValues doesnt catch values.
I am unable to figure out what to write inside. Any help would be appreciated. Thank you.
Try something like this:
$('.limitedNumbSelect').change(function (e) {
$("#limitedNumbSelect > option").each(function () {
var val = $(this).val();
var display = checkedValues.indexOf(val) === -1;
$(this).toggle(display);
});
});
Replace the line:
checkedValues += $(this).val();
In this line:
checkedValues.push($(this).val());
I have 6 input checkboxes and if checkboxes are checked more than 3 the last one gets unchecked. For better understanding refer my previous question. Which is solved.
Now, I have another problem, Now 3 checkboxes are checked already by Math.random. On click of any unchecked checkbox. I'm getting error in console.
Uncaught TypeError: Cannot read property 'prop' of undefined
Fiddle Demo
code below:
var random_checked = $("input[type=checkbox]").get().sort(function(){
return Math.round(Math.random())-0.6; //so we get the right +/- combo
}).slice(0,3);
$(random_checked).prop('checked', true);
var checked = [];
$('input[type=checkbox]').change(function(e) {
var num_checked = $("input[type=checkbox]:checked").length;
if (num_checked > 3) {
checked[checked.length - 1].prop('checked', false);
checked.pop();
}
if($.inArray($(this), checked) < 0){
checked.push($(this));
}
});
You can try the below code
var checked = $('input[type=checkbox]:checked').map(function(){
return $(this);
}).get(); // First change
$('input[type=checkbox]').change(function(e) {
var num_checked = $("input[type=checkbox]:checked").length;
if (num_checked > 3) {
$(checked.pop()).prop('checked', false);// Second change
}
if($.inArray($(this), checked) < 0){
checked.push($(this));
}
});
DEMO FIDDLE
Changes Made
► Stored the currently checked elements to an array using
var checked = $('input[type=checkbox]:checked').map(function(){
return $(this);
}).get();
► $(checked.pop()) is used to select the last inserted element.
Why your code was not working?
As per you code var checked = []; will be empty at the initial stage. So checked[checked.length - 1] will become undefined.
You should push initial items in checked list.
$(random_checked).each(function(){
console.log($(this));
checked.push($(this));
});
https://jsfiddle.net/usx8Lkc5/18/
This one works, just simply adding lastChecked = random_checked[2]; so that your lastChecked is defined.
var random_checked = $("input[type=checkbox]").get().sort(function(){
var test = Math.round(Math.random())-0.6;
return test; //so we get the right +/- combo
}).slice(0,3);
$(random_checked).prop('checked', true);
lastChecked = random_checked[2];
var $checks = $('input:checkbox').click(function(e) {
var numChecked = $checks.filter(':checked').length;
if (numChecked > 2) {
alert("sorry, you have already selected 3 checkboxes!");
lastChecked.checked = false;
}
lastChecked = this;
});
I received some Jquery code for an HTML checkbox. Essentially, when checked, the value of the checkbox is placed in an input box. When I uncheck the box, the value is cleared from the input. However, when you check multiple checkboxes, a "," separates the values. Is there a way to seperate the values by "-" instead of ","? I tried playing around with the code and it just breaks the code. I am fairly new to JS/Jquery so if it is a simple answer, I apologize. I can provide more information if needed. A working JSFiddle with "," is here: https://jsfiddle.net/m240Laka/25/
My code is located here:
var $choiceDisplay = $("#choiceDisplay"), //jquery selector for the display box
$none = $("#none"),
$choice = $(".choice");
$choice.on("change", function () {
var $this = $(this), //jquery selector for the changed input
isThisChecked = $this.prop("checked"), //boolean true if the box is checked
choiceSelectionsArray = $choiceDisplay.val().split(",").filter(function(e){return e !== ""}), //array of values that are checked
isThisValueInDisplayedSelection = $.inArray($this.val(), choiceSelectionsArray) !== -1; //boolean true when $this value displayed
if (isThisChecked) {
if (isThisValueInDisplayedSelection) {
return false; //odd, the value is already displayed. No work to do.
} else {
choiceSelectionsArray.push($this.val());
$choiceDisplay.val(choiceSelectionsArray.join());
}
} else { //box has been unchecked
if (isThisValueInDisplayedSelection) {
choiceSelectionsArray = choiceSelectionsArray.filter(function(e){return e !== $this.val()})
$choiceDisplay.val(choiceSelectionsArray.join());
}
}
});
$none.on("change", function () {
var $this = $(this),
isThisChecked = $this.prop("checked");
if(isThisChecked){
$choice.prop({
disabled: true,
checked : false
});
$choiceDisplay.val("");
}else{
$choice.prop({disabled: false});
return false;
}
});
In the functions join() and split(), you need to pass in the delimiter you want, '-'. I suggest creating a local variable that you use, so it is easier to change this if needed.
var $choiceDisplay = $("#choiceDisplay"), //jquery selector for the display box
$none = $("#none"),
$choice = $(".choice"),
delimiter = '-';
$choice.on("change", function () {
var $this = $(this), //jquery selector for the changed input
isThisChecked = $this.prop("checked"), //boolean true if the box is checked
choiceSelectionsArray = $choiceDisplay.val().split(delimiter).filter(function(e){return e !== ""}), //array of values that are checked
isThisValueInDisplayedSelection = $.inArray($this.val(), choiceSelectionsArray) !== -1; //boolean true when $this value displayed
if (isThisChecked) {
if (isThisValueInDisplayedSelection) {
return false; //odd, the value is already displayed. No work to do.
} else {
choiceSelectionsArray.push($this.val());
$choiceDisplay.val(choiceSelectionsArray.join(delimiter));
}
} else { //box has been unchecked
if (isThisValueInDisplayedSelection) {
choiceSelectionsArray = choiceSelectionsArray.filter(function(e){return e !== $this.val()})
$choiceDisplay.val(choiceSelectionsArray.join(delimiter));
}
}
});
Here is it in a jsfiddle.
In $.join() add the separator string parameter:
$choiceDisplay.val(choiceSelectionsArray.join("-"));
UPDATE:
add the same in $.split()
choiceSelectionsArray = $choiceDisplay.val().split("-")....
I have the following code, which should go through each table row and dump my array which is declared in an earlier segment of javascript. Then if the checkbox is checked, and it has an attr of "changed=yes" then it should be pushed onto the array and the value should be outputted in console as well as the "path" attribute which should be outputted as a variable that can be overwritten every time the function finds a new checkbox that is checked and changed. So what is wrong with my code? These functions are contained in a function that is called when the user clicks submit on the form.
JsFiddle: http://jsfiddle.net/hU89p/392/
$('#myTable1 tr').each(function(){
myArray = [];
$.each($("input[type='checkbox']:checked").closest("td").siblings("td"),
function () {
if($(this).data("changed") == 'yes'){
myArray.push($(this).attr('checkboxtype'));
filepath = $(this).attr('path');
console.log(myArray);
console.log(filepath);
}
});
});
Here is the Working Fiddle :
Keep it simple :
$('#myTable1 tr').each(function() {
var columns = $(this).find('td');
columns.each(function() {
var box = $(this).find('input:checkbox');
if(box.is(":checked") && box.attr("changed") == 'yes')
{
myArray.push(box.attr('checkboxtype'));
filepath = box.attr('path');
}
});
});
console.log(myArray);
});
You should be using $("input[type='checkbox']:checked").closest("td").siblings("td").each().
See the difference between $().each() and $.each().
try this :-
$('#myTable1 tr').each(function () {
myArray = [];
$(this).find("td input:checkbox").each(function () {
if ($(this).is(":checked") && $(this).attr("changed") == 'yes') {
myArray.push($(this).attr('checkboxtype'));
filepath = $(this).attr('path');
console.log(myArray);
console.log(filepath);
}
});
});