show and hide divs with multiple class names jquery checkboxes - javascript

I have many dives with multiple classes as
<div class="my-gallery">
<div class="LargeFace Neutral Happy"></div>
<div class="Sad Neutral Happy"></div>
<div class="LargeFace Surprise Happy"></div>
<div class="LargeFace Fear Happy"></div>
</div>
And I have multiple check boxes which have all those values. e.g LargeFace or Happy and else.
<label class="with-label">
<input id="c_b" type="checkbox" name="r1" value="Neutral" />Neutral
</label>
<label class="with-label">
<input id="c_b" type="checkbox" name="r1" value="LargeFace">Large Face
</label>
Through this code I am getting all those checkbox values to an array
$('.with-label').on "click", ->
allVals = []
$('.with-label :checked').each ->
allVals.push $(this).val()
return
console.log allVals
return
Right now I am really really struggling for filtering my divs on the basis of this array values. for example. User have selected multiple check boxes and create an array as ["Happy", "Fear"]
I want to make something which will filter #my-gallery on the basis on that array. If there are 2 those values in an array then All those divs, which contain that classes should appear and other should disappear, So for other values? Is that possible? please help I am struggling with this for so long

Instead of pushing the values in array, You can create a class selector for the value and then push it in array.
$('.with-label :checked').each ->
allVals.push("." + $(this).val())
return
which will create the array as:
[".LargeFace",".Happy"]
Then use .join() to create the class selectors, traverse to parent and show them :
$('.my-gallery > div').hide(); //hide all first
$(allVals.join(',')).show(); //show based on array values

$('.my-gallery > div').each(() => {
if ($(this).attr('class').split(' ').some(className => allVals.includes(className))) {
$(this).show();
} else {
$(this).hide();
}
});
Place this directly after you create your allVals array.
It goes through all your gallery divs and checks if at least one of the classes belongs to allVals.
Older javascript syntax:
$('.my-gallery > div').each(function() {
if ($(this).attr('class').split(' ').some(function(className) {
return allVals.indexOf(className) !== -1;
})) {
$(this).show();
} else {
$(this).hide();
}
});

Try this.
In previous function of jquery use your element which need to be tackle
$('.with-label').on('click', function(){
$(this).closest('.with-label').prev(your_element).toggle();
});

Related

Get selected value from multiple select on change in dynamic form

I'm currently working on a dynamic form which enables the user to add as many variants as they would like. This form which can be added has a price, size and color. The size and color are select2 select boxes which enable the user to select multiple things. The form:
<div class="col-sm-4">
<label>Kleuren</label>
<select name="colors[{{$i}}][]" id='color-options' class="form-control multiple-select" multiple="multiple">
#foreach($colors as $id=>$color)
<option value="{{$id}}">{{$color}}</option>
#endforeach
</select>
</div>
When looking at the HTML code I have multiple of these forms which go by name: colors[0][], colors[1][], colors[2][] etc.
How do I print the value of a selected new color in a new div? The code which I have thus far:
$(document).ready(function() {
$('.multiple-select').select2({
language: 'nl'
});
$('.summernote').summernote();
var addVariantButton = document.getElementById('addVariant[0]');
addVariantButton.addEventListener('click', function(){
addVariant(0);
});
var colorSelected = document.getElementsByName('colors[0][]');
colorSelected.addEventListener("click", displayColorSelected);
});
function displayColorSelected() {
var selected_value = document.getElementById("color-options").value;
console.log(selected_value);
}
But this only works for the first colors input form, but how can I make this into a more dynamical function to get all colors input?
You can get all selected values in array as below:
function displayColorSelected() {
var selected_value = $("[id='color-options']").toArray().map(x => $(x).val());
console.log(selected_value);
}
Note: id selector will always return single element which will be first with that id. So you're getting value for first select only.
You can use attribute selector ([]) instead which will find every element with given id. So here $("[id='color-options']").toArray() will find every element with id equal to color-options and map(x => $(x).val()) will return only value part from the elements array.
Add all the selects a class ("color-select" for example), and run over all the selects -
$('.color-select').each(function() { console.log($(this).val()); })
You may need to delegate your event listener
document.addEventListener('event',function(e){
if(element){//do something}
})
Since you are using jquery its easier
$(document).on('event','element',function());

Issue removing duplicate val() in :checked .map function

I could use some insight or a helpful reference on where to look for checking values on selected checkboxes and if there are duplicates, only return one.
I'm working on a software trial wizard using bootstrap wizard. The first tab is a "solutions catalog" where the user can filter through hundreds of solutions. Many solution types are duplicate as they apply to multiple industry types.
Once user makes selections they go to tab 2 and review their selections. I'm able to map :checked and join the values in a custom separator in the next step but can't figure out how to only show one instance of a duplicate value.
For example, user might select two types of "Audits" for a customized solution. However, the provisioning team only wants to know that they want an "Audit" module.
<input type="checkbox" class='selection' value="Audits" name="Audits - Manufacturing">
<input type="checkbox" class='selection' value="Audits" name="Audits - Electrical">
<input type="checkbox" class='selection' value="Audits" name="Audits - Retail">
<input type="checkbox" class='selection' value="Trading" name="Trading - Manufacturing">
<input type="checkbox" class='selection' value="Trading" name="Trading - Retail">
My current code is outputting multiple selections of same value and kinda stuck on how to handle this.
$(document).ready(function() {
$('#rootwizard').bootstrapWizard({
onNext: function(tab, navigation, index) {
if (index == 1) {
// Make sure we entered the solutions
if (!$('.selection:checked').val()) {
alert('Please select a solution to try');
$('.selection').focus();
return false;
}
}
// Show selections in next tab
$('#showSelection').html('<li>' + $('.selection:checked').map(function() {
return $(this).val();
}).get().join('</li><li>') + '</li>');
}
});
});
You could use an array to store the values you have already seen. Something like:
$(document).ready(function() {
$('#rootwizard').bootstrapWizard({
onNext: function(tab, navigation, index) {
if (index == 1) {
// Make sure we entered the solutions
if (!$('.selection:checked').val()) {
alert('Please select a solution to try');
$('.selection').focus();
return false;
}
}
var selections = [];
// Show selections in next tab
$('.selection:checked').each(function() {
var value = $(this).val()
if ($.inArray(value, selections) < 0){
selections.push(value);
}
})
$('#showSelection').html('<li>' + selections.join('</li><li>') + '</li>');
}
});
});
fiddle: http://jsfiddle.net/2a460tfc/10/

JS logic - adding 2 multiselect checkboxes

Just need help with a little JS logic as I'm pretty new to it. I have 2 seperate multiselect dropdown checkbox list user can select from. As of now they can choose no more than 5 from each. How could I set it up where it adds boths drop downs to only allow 5 TOTAL for both.
<select id="dropdown1" multiple="multiple" class="multiselect">
<select id="dropdown2" multiple="multiple" class="multiselect">
js
$(document).ready(function() {
$(".multiselect").multiselect({
header: "Choose up to 5 areas",
click: function(event,ui){
if( $(this).multiselect("widget").find("input:checked").length > 5 ){
return false;
}},
selectedList:5
});
I'm assuming I would use the id's instead of just the ".multiselect" class then add them. Something like #dropdown1+#dropdown2 > 5 in the if statement. I just simply don't know proper syntax to go about it someone could help me out.
If your not familiar with the jQuery widget I'm using:http://www.erichynds.com/blog/jquery-ui-multiselect-widget
per request user689
$(document).ready(function() {
$(".multiselect").multiselect({
header: "Choose up to 5 areas",
click: function(event,ui){
if($(".multiselect").multiselect("getChecked").map(function(){
return this.value;
}).size() > 5){ return false;}},
selectedList:5
});
You can do this.
You will show a message and also unselect the item when the number is more than 5.
Javascript using Jquery
$(".multiselect option").click(function(){
if($(".multiselect").children(":checked").length > 5){
if($(this).is(":checked")){
$(this).removeAttr("selected");
alert("You can select only 5 items");
}
}
}
);
The syntax for using a method is:
$("#multiselect").multiselect("method_name");
As an example, to get an array of all clicked checkboxes:
var array_of_checked_values = $(".multiselect").multiselect("getChecked").map(function(){
return this.value;
}).get();
In your case, you just want to get the number of checked boxes, i.e the length of the array:
if($(".multiselect").multiselect("getChecked").map(function(){
return this.value;
}).size() > 5){ return false;}
The method you are using will access each checkbox on its own, and that would complicate things.

Modify this function to display all the checked checkboxes' values (instead of last selected)

I am replicating the functionality of a select/multiselect element and I'm trying to use this function to display the items which have been selected in the relevant container. I need to show all the values that have been selected in a comma-separated list, but it's currently only showing one selection (the last one made). It's also displaying the checkbox, background color, etc. of the list item selected instead of the checkbox value (i.e. value="Black").
I'm using this for a few multiselect form elements where I couldn't use the jQuery UI MultiSelect Widget because they needed to be styled in a very specific way (options displayed with background colors or images and spread out over several columns, etc.).
I've included the relevant code below, and I've posted a working example of the styled 'faux'-multiselect element here: http://jsfiddle.net/chayacooper/GS8dM/2/
JS Snippet
$(document).ready(function () {
$(".dropdown_container ul li a").click(function () {
var text = $(this).html();
$(".dropdown_box span").html(text);
});
function getSelectedValue(id) {
return $("#" + id).find("dropdown_box span.value").html();
}
});
HTML Snippet
<div class="dropdown_box"><span>Colors</span></div>
<div class="dropdown_container">
<ul>
<li><a href="#"><div style="background-color: #000000" class="color" onclick="toggle_colorbox_alt(this);" title="Black"><div class=CheckMark>✓</div>
<input type="checkbox" name="color[]" value="Black" class="cbx"/></div>Black</a>
</li>
<!-- More list items with checkboxes -->
</ul>
</div>
I've tried several other methods (including many of the ones listed here: How to retrieve checkboxes values in jQuery), but none of those worked with hidden checkboxes and/or the other functions I need to incorporate in these particular form elements.
well, to start with change click(..){..} in document.ready to
$(".dropdown_container ul li a").click(function () {
var text = $(this).html();
var currentHtml = $(".dropdown_box span").html();
var numberChecked = $('input[name="color[]"]:checked').length;
$(".dropdown_box span").html(currentHtml.replace('Colors',''));
if (numberChecked > 1) {
$(".dropdown_box span").append(', ' + text);
} else {
$(".dropdown_box span").append(text);
}
});
this will do the appending of text right.
however I couldn't understand the handling of images in the code.
Update, to handle just the value:
replace var text = $(this).html(); with
var text = $(this).find("input").val();
It might be easier to just grab all the values of the check boxes whenever the click event is triggered and then append the values to your span. Like http://jsfiddle.net/9w95b/
I would also suggest not putting the <input> tags inside your <a> tags.

Run each for a class but once for group

I have a lot of elements with the same class. These elements are divided into groups by means of attribute "data-xxx"
<div class="myclass" data-n="group1"></div>
<div class="myclass" data-n="group1"></div>
<div class="myclass" data-n="group1"></div>
....
<div class="myclass" data-n="group2"></div>
<div class="myclass" data-n="group2"></div>
...
<div class="myclass" data-n="group3"></div>
...
...
How to perform a function on each item, but only once in each group using something like this?
$('.myclass').each(function(){
/// My function
});
Working example: http://jsfiddle.net/5sKqU/1/
$(document).ready(function() {
var group = {}; //an object that we're going to use as a hash
$('.myclass').each(function(){
if (group[$(this).attr('data-n')] != true) {
group[$(this).attr('data-n')] = true;
//do something here once per each group
alert('Group: '+ $(this).attr('data-n'));
}
});
});
I'm assuming that you only need this to run once on page load. If you could share more about your requirements, I can show you what changes you'll need to make.
Something like this maybe :
var groups = {};
$('.myclass').each(function(i, el) {
var n = $(el).data('n');
if(!groups[n]) {
groups[n] = $();
}
groups[n] = groups[n].add(el);
});
//At this point the object `groups` has one property per group,
//each value being a jquery collection comprising members of the group.
//Now the world's your oyster. You can loop through the groups
//with full access to each group's members if necessary.
$.each(groups, function(groupName, jq) {
//my function
});
You can set a certain HTML attribute on all group elements after processing the first one. After that, you can check the value of that attribute:
$('.myclass').each(function(){
if($(this).attr("processed")!="true") {
// process...
$("[data-n=" + $(this).attr("data-n")).attr("processed", "true");
} else {
// skip, or do something else with the element
}
});
You can select out each group with the jQuery attribute selector, like this:
$( '.myclass[data-n="groupX"]' );
I'm not sure if you meant that you only wanted to apply your function to one element in each group, but if so this will give you only the first in each:
$( '.myclass[data-n="groupX"]' ).first();
Given that you label your groups 1 through N you can just check if there is anything in the resulting set to determine when you have looped through every group.

Categories

Resources