List of checkboxes checked for specific classes - javascript

I would like to get a list of names of which checkboxes are checked in a specific DIV (page-wrap). I am creating a filter of sorts and have a treeview of different types like color, quality, grain, etc... Each has its own class assigned to them. Color has a class of color_cb, Quality is product_cb, Grain is grain_cb. The following code works great for any one of them but I'd like to test for all 3. Is there a way to modify this for all 3.
var selected = [];
$('#page-wrap input:checkbox.color_cb:checked').each(function() {
selected.push($(this).attr('name'));
});
alert(selected.join(","));
I've tried this but it doesn't work.
var selected = [];
$('#page-wrap input:checkbox.color_cb:checked input:checkbox.product_cb:checked').each(function() {
selected.push($(this).attr('name'));
});
alert(selected.join(","));

use comma separator b/w selected element
$('#page-wrap input:checkbox.color_cb:checked ,#page-wrap input:checkbox.product_cb:checked')
^^^^-- add , seperator
or use map()
var selected = $('#page-wrap input:checkbox.color_cb:checked ,#page-wrap input:checkbox.product_cb:checked').map(function () {
return $(this).attr('name');
}).get();

'#page-wrap input:checkbox.color_cb:checked input:checkbox.product_cb:checked'
this query selector means that input:checkbox.product_cb:checked is child of input:checkbox.color_cb:checked
But, i think you are looking for elements that accomplish one OR the other query, for that you have to use a comma separator, like this:
'#page-wrap input:checkbox.color_cb:checked, #page-wrap input:checkbox.product_cb:checked'

Simply removing the class should work fine.
var selected = [];
$('#page-wrap input:checkbox:checked').each(function() {
selected.push($(this).attr('name'));
});
alert(selected.join(","));
http://jsfiddle.net/60hnvnh9/1/
If there are checkboxes that you want to avoid targeting, simply give the checkboxes another, common class, and target that.

Related

Detect if a div with id including number is clicked

My html code has X elements, with their ids in this form:
viewer_mX
Here, X is a number from 1 to m (m can be different each time).
I want to use javascript to get the number X of the respective element when somebody clicks one of these elements.
I realise I should probably use a class (.viewer) and and id (#x) containing the number. However, I am using a library to generate the html elements and I am stuck with this protocol and will have to make the best of it.
This is the javascript I have so far:
$(document).ready(function () {
$("#viewer>...").click(function () {
x = ...
var number = x;
});
});
What's missing in this code (indicated by 3 dots) is that viewer is not the full ID, but could be post-pended with something. I want to store whatever is after the clicked div in number, but I can't figure out which function to use for that.
Try this,
$("[id^='viewer_']").click(function () {
var number = this.id.match(/\d+$/)[0];
});
Why not use class to identify elements and then data-attribute for storing your id (data-id for example) and then get value of this data-attribute?
Otherwise I would personally use something like this
$(this).attr('id').substr("viewer_m".length);
Either split or a reg exp
var id = this.id.split("_m")[1]
or
var id = this.id.match(/\d+$/)[0];
or better yet, use a data attribute
<div data-mid="123">
and reference it
$("[data-mid]").on("click", function () {
var id = $(this).data("mid");
});
A better approach to this, as #Wax Cage mentioned, is to use classes and data attributes for better organizing. Example:
<div class="viewer" data-viewer-id="1">...</div>
$('.viewer').on('click', function() {
var viewerId = $(this).data('viewerId');
// ...
});

array push function not working on google chrome

I want to fetch multiple checkboxes values from one div. My code executes successfully on firefox but in other browsers it doesn't work. My code looks like
var amenity_array = [];
var listofParameters = $("#room-amenity input:checkbox");
for (var index in listofParameters) {
if ($(listofParameters[index]).attr('checked')) {
var ste = $(listofParameters[index]).attr('value');
amenity_array.push(ste);
}
}
alert(amenity_array);
in the above code amenity_array alerts within the braces but out of this it doesn't work on chrome.
Couple of suggestions/bugs:
Make sure your selector is correct to select checkboxes
Use :checked to select only the checkboxes that are checked
Don't use for...in for looping over array
You can use each() to get the checked checkboxes and add them in your array
Make sure that at-least one checkbox is selected, otherwise the array will have no elements in it
Code:
var amenity_array = [];
$('#room-amenity input:checkbox:checked').each(function() {
amenity_array.push($(this).val());
});
console.log(amenity_array);

jQuery: Remove and Re-Add Classes

I've searched quite a bit before asking this question, but I may be searching / asking the wrong question:
I want to select the last two classes of an element (that has multiple classes and an unknown amount of classes) and store that in a variable. I then want to remove those two classes and add them back at a later point (like toggleClass). The first class is known, while the second class is unknown.
For instance:
<div class="c1 c2 c3 c-unknown"></div>
I would like to select c3 and c-unknown
I've tried split() and it seems like the solution, but I couldn't quite get it to work.
I appreciate any help / guidance you can offer.
You could store them on the element itself allowing to isolate multiple instances
Following solution doesn't need classes to be in any specific order or matter how many classes are on element.
$('.c1').each(function () {
/* array of classes on elemnt*/
var classes = $(this).attr('class').split(' ');
/* remove the targeted selector from array */
classes.splice(classes.indexOf('c1'), 1);
/* remove the extra classes from element and store */
$(this).removeClass(classes.join(' ')).data('classes', classes);
});
For a specific element could also use attr(function)
$('.c1.Specific').attr('class', function(_, existingClasses){
var classes = existingClasses.split(' ');
classes.splice(classes.indexOf('c1', 1));
$(this).data('classes', classes);
return 'c1';
});
Then to re-use the stored classes
var $el = $('.c1:first');
$el.addClass( $el.data('classes').join(' '))
DEMO
Probably the easiest way to get the last two classes:
var lastTwoClasses = $('.c1').attr('class').split(/\s+/).slice(-2).join(' ');
Toggle (for example with button id="btn"):
$('#btn').click(function(){
$('.c1').toggleClass(lastTwoClasses);
});
JSFiddle
EDIT.
And yet another way:
$('.c1').each(function(){
var classes = $(this).attr('class').split(/\s+/).slice(-2).join(' ');
$(this).click(function(){
$(this).toggleClass(classes);
});
});
JSFiddle
I believe this is what you're trying to do.
var ele = document.getElementsByClassName('c1'),
classes = ele[0].className,
classArr = classes.split(' '),
spliceIndex = classArr.length - 2,
last2Classes = classArr.splice(spliceIndex, 2);
Here's a working fiddle
If you're trying to remove the classes you can use jquery or you could just use the dom element's className property and set it to whichever array has the classes you want to use. You would use the array method .toString() on either array and it will give you a string representation of the classes.
The answer here could help you to get part of the functionality you need:
Get first and last class with jQuery
Starting with that, you could use split, and removeClass like this
(sample text and css added for demo purposes):
function removeTheClasses(el) {
var classes = el.attr("class").split(/\s/);
var second_to_last = classes[classes.length - 2]; //second to last class
var last = classes[classes.length -1]; //last class
el.removeClass(second_to_last, last);
}
$('button').click(function() {
removeTheClasses($('.c1'));
});
.c-unknown {font-weight:bold}
.c3 {color:pink}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="c1 c2 c3 c-unknown">
ABC
</div>
<br/>
<button>Remove the last two classes</button>
In order to add these same classes back in (toggling), you'd have to keep a record of the recently removed classes. This would require:
pushing the values of the first & last variables to a cookie or web storage (if handling multiple elements at a time), OR
a single javascript variable above the scope of the 'removeTheClasses' function (if you're just handling one element at a time).

How to hide multiple elements

I want to hide multiple elements when I press a button which get the value of checkboxs, and if the checkbox is checked it's hide.
I have the next code, but it just work with the first element
var checkedInputs = $("input:checked");
var test = "";
$.each(checkedInputs, function(i, val) {
test += val.value+",";
});
test = test.substring(0,(test.length-1));
$("#numRow"+test).hide('slow'); // it should to hide multiple elements, but just work with the first value
I also tried with array, but it doen't work too.
var numMsj =[1, 2, 4, 22, 44,90, 100];
$.each(numMsg, function (ind, elem) {
$("#numRow"+elem).hide('slow');
});
The modified solution
You could just put the hide inside the each loop:
var checkedInputs = $("input:checked");
$.each(checkedInputs, function(i, val) {
test += val.value+",";
$(this).hide('slow');
});
Here is a working example
The one-liner
Or if you don't need the test variable at all, you can do it is a single line:
$("input:checked").hide('slow');
Here is an example on that
The problem with your attempts
Just for reference, the reason your first example doesn't work is because your selector ends up looking like this:
$("#numRow1,2,4")
Which will select the first element with id numRow1, and then tags called 2 and 4, which won't exist. You would want to create your selector to look like the following:
$("#numRow1,#numRow2,#numRow4")
However, this is just an example, my alternative methods above are a much better approach.
The problem with your second attempt is simply a typo between numMsj and numMsg.

Javascript array not working as expected

I'm pretty new to js/jquery. For each checkbox with the ID of check$ (where $ is a sequential number), I want to toggle the class "agree" of the surrounding span that uses the same check$ (but as a class). I don't want to have to hard-code the list of matching checkboxes, as this may vary.
Here's my code. This function works as expected:
agree = function (checkbox, span) {
$(checkbox).change(function(){
$(span).toggleClass('agree');
});
};
This is what I'm trying to pass to the above function, which does not work:
$(function() {
var elemid = 'check',
checks = Array($('[id^='+elemid+']').length);
console.log(checks);
for (i=0; i < checks; i++) {
agree('#'+elemid+checks[i], "."+elemid+checks[i]);
}
});
console.log(checks) returns [undefined × 4]. The number of elements is correct, but I don't know why it's undefined, or whether that is even significant.
The following code works as expected, but as I say, I'd rather not have to specify every matched element:
$(function() {
var checks = ["check1", "check2", "check3", "check4"];
for (i=0; i < checks.length; i++) {
agree('#'+checks[i], "."+checks[i]);
}
});
Thanks.
Edit: Thanks to Jack, I was overlooking the most simple method. I added the same class to all checkboxes and spans, and solved the problem with this:
$('input.check').change(function(){
$(this).closest('span.check').toggleClass('agree');
});
I might be totally missing something, but I'm pretty sure you are just trying to attach a change handler to each checkbox. In this case you can give them all the same class. I'm also guessing at your html structure for the span.
For reference:
http://api.jquery.com/closest/
http://docs.jquery.com/Tutorials:How_jQuery_Works
$('.yourcheckboxclass').change(function(){ //grab all elements with this class and attach this change handler
$(this).closest('span').toggleClass('agree');
});
The reason that the array is full of undefined values, is that you are just getting the number of items in the jQuery object, and create an array with that size. The jQuery object is discarded.
Put the jQuery object in the variable instead:
var elemid = 'check', checks = $('[id^='+elemid+']');
checks.each(function(){
agree(this, "."+elemid+checks[i]);
});

Categories

Resources