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

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

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

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.

How to use jQuery select / .change() to reveal a hidden div

I have the following select field and based on whether the class .show-x-trend or show-x is selected I would like to conditionally reveal a separate div. If .show-x-trend <option> is selected, I'd like to reveal the already hidden #x-axis-trend-wrap <div> and if show-x option is selected I'd like to reveal the already hidden #x-axis-wrap <div>. In the code below, you'll see that I have both CSS classes and also values assigned to the 3 selection options because I tried to achieve the effect a few different ways but so far with no luck.
<div id="visualize-wrap">
<h3>Visualization Shows</h3>
<select id="visualize-shows" name="visualize">
<option class="no-show" value="00">Select One</option>
<option class="show-x-trend" value="01">Trend Over Time</option>
<option class="show-x" value="02">Breakdown of Sum Total</option>
<option class="show-x" value="03">Side-by-side Comparison</option>
</select>
</div>
You can use hasClass method to determine if the selected option contains the required class or not and act accordingly.
$('#visualize-shows').change(function(){
var $selectedOption = $(this).find('option:selected');
$('#x-axis-trend-wrap')
.toggle( $selectedOption.hasClass('show-x-trend'));
$('#x-axis-wrap')
.toggle( $selectedOption.hasClass('show-x'));
});
Working demo - http://jsfiddle.net/X2dPt/
Try something like this
$("#visualize-shows").change(function() {
$selected = $(this).find('option:selected'); // get selected option
if ($selected.hasClass('show-x-trend')) { // check the class
$('#x-axis-trend-wrap').toggle(); // toggle display
} else if ($selected.hasClass('show-x')) {
$('#x-axis-wrap').toggle();
}
});
this uses .hasClass()

Filtering table with jQuery

I have this table which has seven columns, each column representing a specific value like so:
I also have five select boxes containing options which I want to use for filtering this data table.
So far, I have come up with this:
$('#mySelectBox').change(function() {
var filtervar = $(this).val();
$('tr td.someclass').each(function () {
if ($(this).text() != filtervar) {
$(this).parent().hide();
} else {
$(this).parent().show();
}
});
});
This code works for one selectbox. How can I tweak it so that I can use five different selectboxes for filtering?
It is already generic enough. Just change the select box from having ids to classes and target all select boxes with the proper class.
Script:
$('.filter').change(function() { /* ... code ... */ });
HTML:
<select class="filter"> ... </select>
<select class="filter"> ... </select>
<select class="filter"> ... </select>
How can I tweak it so that I can use five different selectboxes for
filtering?
Simply apply a class to all your select boxes, this way you will need only one selector:
$('.selectBox').change.....
Just give your select lists all the same class, such as "mySelectClass", and then use that in the selector instead of an ID.
$('.mySelectClass').change(function() {

Changing selection in a select with the Chosen plugin

I'm trying to change the currently selected option in a select with the Chosen plugin.
The documentation covers updating the list, and triggering an event when an option is selected, but nothing (that I can see) on externally changing the currently selected value.
I have made a jsFiddle to demonstrate the code and my attempted ways of changing the selection:
$('button').click(function() {
$('select').val(2);
$('select').chosen().val(2);
$('select').chosen().select(2);
});
From the "Updating Chosen Dynamically" section in the docs: You need to trigger the 'chosen:updated' event on the field
$(document).ready(function() {
$('select').chosen();
$('button').click(function() {
$('select').val(2);
$('select').trigger("chosen:updated");
});
});
NOTE: versions prior to 1.0 used the following:
$('select').trigger("liszt:updated");
My answer is late, but i want to add some information that is missed in all above answers.
1) If you want to select single value in chosen select.
$('#select-id').val("22").trigger('chosen:updated');
2) If you are using multiple chosen select, then may you need to set multiple values at single time.
$('#documents').val(["22", "25", "27"]).trigger('chosen:updated');
Information gathered from following links:
1) Chosen Docs
2) Chosen Github Discussion
Sometimes you have to remove the current options in order to manipulate the selected options.
Here is an example how to set options:
<select id="mySelectId" class="chosen-select" multiple="multiple">
<option value=""></option>
<option value="Argentina">Argentina</option>
<option value="Germany">Germany</option>
<option value="Greece">Greece</option>
<option value="Japan">Japan</option>
<option value="Thailand">Thailand</option>
</select>
<script>
activateChosen($('body'));
selectChosenOptions($('#mySelectId'), ['Argentina', 'Germany']);
function activateChosen($container, param) {
param = param || {};
$container.find('.chosen-select:visible').chosen(param);
$container.find('.chosen-select').trigger("chosen:updated");
}
function selectChosenOptions($select, values) {
$select.val(null); //delete current options
$select.val(values); //add new options
$select.trigger('chosen:updated');
}
</script>
JSFiddle (including howto append options):
https://jsfiddle.net/59x3m6op/1/
In case of multiple type of select and/or if you want to remove already selected items one by one, directly within a dropdown list items, you can use something like:
jQuery("body").on("click", ".result-selected", function() {
var locID = jQuery(this).attr('class').split('__').pop();
// I have a class name: class="result-selected locvalue__209"
var arrayCurrent = jQuery('#searchlocation').val();
var index = arrayCurrent.indexOf(locID);
if (index > -1) {
arrayCurrent.splice(index, 1);
}
jQuery('#searchlocation').val(arrayCurrent).trigger('chosen:updated');
});

Categories

Resources