JS logic - adding 2 multiselect checkboxes - javascript

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.

Related

Tampermonkey: Hide Options in Dropdown if they don't contain a string

I am working on a Tampermonkey script to make life a lot easier. So picture this: There's a dropdown supplying 400+ options. However, I only need to use two of them. So all the others can be hidden.
So how do I do this? Currently, I am working with this, but it doesn't really do what I want it to.
var firstCampaignName = "001 - Campaign";
var secondCampaignName = "002 - Campaign";
These are the two options I want to keep. I halfway think I could simplify this by matching them both on " - Campaign" or something. Because the names are nigh-identical. But anyway. So here's the function I'm working with.
$('#dropdown option').each(function(){
if ('#dropdown option'.text() === firstCampaignName || '#brand option'.text() === secondCampaignName)
{
if ($.inArray($(this).text()))
$(this).show();
// If not, hide it
else
$(this).hide();
}
});
It's obvious that I'm doing something wrong. Somewhere in this, I am missing something. So, please, help?
To hide all options from the dropdown except the 2 specific options you can do the following. Note that as mentioned as comment by charlietfl that to hide options is not supported cross browser, so maybe it's an option for you to remove those options instead of hiding them as you mentioned that you don't need them.
var firstCampaignName = "001 - Campaign";
var secondCampaignName = "002 - Campaign";
$('#dropdown option').each(function() {
if ($(this).text() === firstCampaignName || $(this).text() === secondCampaignName) {
$(this).show();
} else {
$(this).hide();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="dropdown">
<option value="1">001 - Campaign</option>
<option value="2">002 - Campaign</option>
<option value="3">003</option>
<option value="4">004</option>
<option value="5">005</option>
</select>

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());

show and hide divs with multiple class names jquery checkboxes

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();
});

jQuery - if select option value equal with a data add class

I have a select box with 3 option, and a div with 3 that they has data attribute.
now i want each option that has selected=seclected and also value (number) equal with a data then add class to
for example:
if option selected / and value = with data:
<option value="2" selected="selected">
do (add class):
<a class="menuitem active" data="2"></a>
JSFiddle
$("#myselect option").each(function(){
var num = $('.menucontainer').children('a.menuitem').attr('data');
if($(this).is(':selected').val()==num){
$('.menucontainer').children('a.menuitem').addClass('active');
}
});
});
You had many small mistakes. Like
1.) Jquery was not included in fiddle.
2.) .is returns a boolean value, and you were doing $(this).is(':selected').val(). You should be doing $(this).is(':selected') && $(this).val().
3.) There was }); extra in the end.
And I think iterating other way arround will be better. Like bellow
$('.menucontainer .menuitem').each(function(){
if($(this).attr('data')==$('#myselect :selected').val())
$(this).addClass('active');
})
DEMO

Using custom jQuery radio buttons with CakePHP Form Helper

I'm using a custom jQuery plugin to convert radio buttons to actual images, and it works with basic checkboxes, but when using Cake's built-in input form helper, it acts more as a checkbox by not unchecking the already clicked options. Not only that, but it isn't populating $this->data (or sending anything when the form is submitted).
The js looks like this:
//##############################
// jQuery Custom Radio-buttons and Checkbox; basically it's styling/theming for Checkbox and Radiobutton elements in forms
// By Dharmavirsinh Jhala - dharmavir#gmail.com
// Date of Release: 13th March 10
// Version: 0.8
/*
USAGE:
$(document).ready(function(){
$(":radio").behaveLikeCheckbox();
}
*/
$(document).ready(function() {
$("#bananas").dgStyle();
var elmHeight = "15"; // should be specified based on image size
// Extend JQuery Functionality For Custom Radio Button Functionality
jQuery.fn.extend({
dgStyle: function()
{
// Initialize with initial load time control state
$.each($(this), function(){
var elm = $(this).children().get(0);
elmType = $(elm).attr("type");
$(this).data('type',elmType);
$(this).data('checked',$(elm).attr("checked"));
$(this).dgClear();
});
$(this).mouseup(function() {
$(this).dgHandle();
});
},
dgClear: function()
{
if($(this).data("checked") == true)
{
$(this).addClass("checked");
}
else
{
$(this).removeClass("checked");
}
},
dgHandle: function()
{
var elm = $(this).children().get(0);
if($(this).data("checked") == true)
$(elm).dgUncheck(this);
else
$(elm).dgCheck(this);
if($(this).data('type') == 'radio')
{
$.each($("input[name='"+$(elm).attr("name")+"']"),function()
{
if(elm!=this)
$(this).dgUncheck(-1);
});
}
},
dgCheck: function(div)
{
$(this).attr("checked",true);
$(div).data('checked',true).addClass('checked');
},
dgUncheck: function(div)
{
$(this).attr("checked",false);
if(div != -1)
$(div).data('checked',false).css({
backgroundPosition:"center 0"
});
else
$(this).parent().data("checked",false).removeClass("checked");
}
});
The PHP/Html looks like this:
<span id="bananas-cat" class="cat">
<?= $this->Form->radio('bananas',array(),array('legend' => false, 'id' => 'bananas', 'name' => 'category')); ?>
<label for="bananas">Bananas</label>
</span>
While it upon first inspection may look correct, when clicked, nothing gets passed within $this->data and it acts like a checkbox and doesn't unselect the value when I add an additional radio checkbox.
Although the radio functionality does work without CakePHP's html form helper like so:
<span id="animals-cat" class="cat">
<input type="radio" name="category" id="animals" />
<label for="animals">Animals</label>
</span>
If anyone can help me out here, I would be forever indebted. I've been trying to solve this for way too long now that I'm considering just scrapping the whole idea to begin with.
What I would suggest is see and compare the HTML output of example and one being generated by CakPHP, try to make it similar to example so that you can get your custom-radio-buttons working.
But if you can not do that I would highly recommend to override those helpers by some parameters so that you can get the exact HTML as an output and Javascript should work flawlessly.
Let me know if that does not work for you.

Categories

Resources