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

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

Related

Set select option by index

I have a dynamically generated dropdown select feature that numerically pages through a book. I wish to create a table of content feature that allows users to click a link to jump to pages within the book. I've implemented a vanilla javascript solution (see below) that selects by index BUT the update isn't triggered (page number changes in the pager but it doesn't advance the page).
I welcome a way to make the javascript change trigger or a jquery solution. Thanks!
function selectOption(index) {
document.getElementById("tei_pager").options.selectedIndex = index;
}
<select id="tei_pager" class="form-select">
<option value="10917">1</option>
<option value="10918">2</option>
<option value="10919">3</option>
</select>
Second Page
and this section of a separate jquery is binding the select
// Bind page changes to the select.
$("#tei_pager").change(function () {
Drupal.settings.islandora_paged_tei_seadragon_update_page(
$(this).val(),
$(this).children("option:selected").text()
);
});
I adapted a solution from here: Change <select>'s option and trigger events with JavaScript
Having the selection made by js rather than a mouseclick was inhibiting the process.
My solution looks like:
js
function selectOption(index){
if (index == 0) {
document.getElementById("tei_pager").options.selectedIndex = index;
}
else {
document.getElementById("tei_pager").options.selectedIndex = (index - 1);
}
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
document.getElementById("tei_pager").dispatchEvent(evt);
}
else {
document.getElementById("tei_pager").fireEvent("onchange");
}
}
html
<select id="tei_pager" class="form-select">
<option value="10917" selected="selected">1</option>
<option value="10918">2</option>
<option value="10919">3</option>
<option value="10920">4</option>
<option value="10921">5</option>
<option value="11192">6</option>
<option value="11193">7</option>
</select>
First Page
Sixth Page
You can set the value of the select tag.
function selectOption(val) {
document.getElementById("tei_pager").value = val;
}
<select id="tei_pager" class="form-select">
<option value="10917">1</option>
<option value="10918">2</option>
<option value="10919">3</option>
</select>
Second Page
If the change event of the select element is to trigger the Drupal code you have at the end of your question,
then change:
$("#islandora_paged_tei_seadragon_pager").change(function () { ....
to:
$("#tei_pager").change(function () { ....
UPDATE
If by ....dynamically generated dropdown select.... you mean to say that the select element is created after DOM ready event, then consider re-writing it as follows:
$(document).on('change', '#tei_pager', function () { ....

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

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

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