Show/Hide based on dropdown option - javascript

I'm using Jquery to show/hide divs based on what a user selects in a dropdown.
My HTML:
<select>
<option value='test'>Test</option>
<option value='example'>Example</option>
<option value='blah'>Blah</option>
</select>
<div data-show="blah">Should be shown when blah</div>
<div data-hide="example">Should be hidden when example</div>
My Jquery (in coffeescript):
$("select").on "change", () ->
shows = $('[data-show="' + $(this).val() + '"]')
hides = $('[data-hides="' + $(this).val() + '"]')
shows.show()
hides.hides()
This works when a user chooses the right option, say Example. But when a user goes back to say Test, it should go back to the default. How do I get this to work?

Can use filter() to set final display and do opposite on whole group before the filter
$("select").on("change", function(){
var value = this.value
// hide all data-show
$('[data-show]').hide().filter(function(){
return $(this).data('show') === value;
}).show()// only show matching ones
$('[data-hide]').show().filter(function(){
return $(this).data('hide') === value;
}).hide()
}).change()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value='test'>Test</option>
<option value='example'>Example</option>
<option value='blah'>Blah</option>
</select>
<div data-show="blah">Should be shown when blah</div>
<div data-hide="example">Should be hidden when example</div>

I dont know what you are up to but this is the described behavior, probably not the desired :D
$('select').on('change', (e) => {
// apply defaults, then filter // credits to filter #charlietfl
$('[data-show]').hide().filter('[data-show=' + $(e.target).val() + ']').show();
$('[data-hide]').show().filter('[data-hide=' + $(e.target).val() + ']').hide();
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value='test'>Test</option>
<option value='example'>Example</option>
<option value='blah'>Blah</option>
</select>
<div data-show="blah">Should be shown when blah</div>
<div data-hide="example">Should be hidden when example</div>
EDIT added default hide/show

$(function(){
$('div').hide();
$('select').change(function(){
if($(this).val()=='blah'){
$('div[data-show]').show();
$('div[data-hide]').hide();
}else if($(this).val()=='example'){
$('div[data-hide]').show();
$('div[data-show]').hide();
}else{
$('div[data-hide]').hide();
$('div[data-show]').hide();
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
<option value='test'>Test</option>
<option value='example'>Example</option>
<option value='blah'>Blah</option>
</select>
<div data-show="blah">Should be shown when blah</div>
<div data-hide="example">Should be hidden when example</div>

Create a selection of your elements you want to show/hide:
var elements = $('[data-show], [data-hide]');
Then you can use jQuery's .filter function to show only the selected element:
var elements = $('[data-show], [data-hide]');
function showElement(option) {
var filter;
// hide all elements befor filtering
elements.hide();
// create the filter value, which will be used for filtering
switch (option) {
case 'test':
filter = '[data-hide="example"]';
console.log('show only example');
break;
case 'blah':
filter = '*';
console.log('show all elements');
break;
default:
console.log('hide all elements (including example)');
break;
}
if (filter) {
elements.filter(filter).show();
}
}
showElement('test');
$("select").on("change", function() {
showElement($(this).val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value='test'>Test</option>
<option value='example'>Example</option>
<option value='blah'>Blah</option>
</select>
<div data-show="blah">Should be shown when blah</div>
<div data-hide="example">Should be hidden when example</div>
Also you had several typos:
When you select the element via data-hide, there's an additional s (hides):
hides = $('[data-hides="' + $(this).val() + '"]')
When you want to hide hides via calling .hides(), jQuery only has a .hide() function to hide an element:
hides.hides()

Let's assume you assume a set of divs, some of which you wish to show/hide based on what you select in a dropdown list, in jQuery.
This is how it can be achieved.
The grid
<div class="row exhbitors-grid-row">
<div class="col-lg-6 col-md-6 exhibitor-grid-item" style="">
<div class="exhibitor-grid-large wow pixFadeRight" data-wow-delay="0.5s" style="visibility: visible; animation-delay: 0.5s; animation-name: pixFadeRight;">
<div class="member-avater">
<img src="#" alt="">
</div>
<div class="listing-page-exhibitor-brief wow pixFadeUp" style="visibility: visible; animation-name: pixFadeUp;">
<div class="exhibitor-details">
<input type="hidden" name="industry" class="industry Accommodation" value="Accommodation">
<h4 class="grid-exhibitor-title">Tourist Board</h4>
<strong class="grid-exhibitor-copy">Manning the Booth</strong>
<div class="grid-item-host">
<span>User</span>
<a href="bcard.pdf" target="_blank" title="Download business card"><i class="fa fa-address-card b-card-file" aria-hidden="true"></i>
</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-6 col-md-6 exhibitor-grid-item" style="">
<div class="exhibitor-grid-large wow pixFadeRight" data-wow-delay="0.5s" style="visibility: visible; animation-delay: 0.5s; animation-name: pixFadeRight;">
<div class="member-avater">
<img src="#" alt="">
</div>
<div class="listing-page-exhibitor-brief wow pixFadeUp" style="visibility: visible; animation-name: pixFadeUp;">
<div class="exhibitor-details">
<input type="hidden" name="industry" class="industry Airline" value="Airline">
<h4 class="grid-exhibitor-title">Tourist Board</h4>
<strong class="grid-exhibitor-copy">Manning the Booth</strong>
<div class="grid-item-host">
<span>User</span>
<a href="bcard.pdf" target="_blank" title="Download business card"><i class="fa fa-address-card b-card-file" aria-hidden="true"></i>
</a>
</div>
</div>
</div>
</div>
</div>
...
...
...
</div>
Somewhere on the page,you have a dropdown list which looks like this:
<select class="category-select" name="category-select" id="category-select">
<option value="-1">Industry </option>
<option value="1">Accommodation</option>
<option value="2">Airline</option>
<option value="3">Car Rentals</option>
<option value="4">City Tourist Board</option>
...
...
...
</select>
On change of this dropdown list, we only want to show the div that has a hidden field value value same as the selected dropdown item. Check the hidden field values above in the div.
We need a small bit of jQuery to do the magic. This is how it will look:
$(document).ready(function(){
if($(".category-select")){
$(".category-select").change(function(){
$(".exhibitor-grid-item").show();
var selectedIndustry = $(".category-select option:selected").text();
$(".exhibitor-grid-item").each(function(){
var $itemIndustry = $(this).find(".industry").val();
if($(".category-select option:selected").val() > -1){
if(selectedIndustry != $itemIndustry){
$(this).find(".industry").parent().parent().parent().parent().hide();
}
}
});
});
}
});

<select class="selectBoxClass">
<option value='test'>Test</option>
<option value='example'>Example</option>
<option value='blah'>Blah</option>
</select>
<div data-show="blah" class="all ">Should be shown when blah</div>
<div data-hide="example" class="all">Should be hidden when example</div>
<script>
$(document).on('change', '.selectBoxClass', function(event) {
event.preventDefault();
$('div.all').show();
shows = $('[data-show="' + $(this).val() + '"]')
hides = $('[data-hides="' + $(this).val() + '"]')
shows.show()
hides.hides()
});
</script>
**if your previous code is not working well, then you can try this.

Related

Filter with select options values

I have a categories dropdown and multiple divs with class names, i want when the user selects and option from the dropdown to filter the divs according to the chosen option, like for example i have a category called makeup when the user selects it i want to only show the divs with the class makeup, here is what i have tried:
$('#categories').change(function() {
var val = $(this).val();
if (val == "makeup") {
$('.makeup').fadeIn();
} else {
$(".makeup").not('.' + value).fadeOut();
$('.makeup').filter('.' + value).fadeIn();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="categories">
<option selected disabled>Choose category</option>
<option value="makeup">Make-up</option>
<option value="cafes">Cafes</option>
<option value="other">Other</option>
</select>
<div class="makeup">
Div 1
</div>
<div class="makeup">
Div 2
</div>
<div class="makeup">
Div 3
</div>
<div class="other">
Div 4
</div>
Put a common class "category" on all the divs.
Bind the change handler to the select
When it changes, fadeOut all the options, and fadeIn the ones that match the value as a class
$('#categories').on('change', function(e) {
$('.category')
.fadeOut()
.filter('.'+ e.target.value)
.fadeIn();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="categories">
<option selected disabled>Choose category</option>
<option value="makeup">Make-up</option>
<option value="cafes">Cafes</option>
<option value="other">Other</option>
</select>
<div class="category makeup">
Div 1
</div>
<div class="category makeup">
Div 2
</div>
<div class="category makeup">
Div 3
</div>
<div class="category other">
Div 4
</div>
This code works as requested, I've just added the class .category-option to the elements you are fading in and out.
Demo
$('#categories').change(function() {
// Get value of selected option
var val = $(this).children("option:selected").val();
// Fadeout all that are not linked
$(".category-option").fadeOut();
// Fade in appropriate options
$(".category-option." + val).fadeIn();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="categories">
<option selected disabled>Choose category</option>
<option value="makeup">Make-up</option>
<option value="cafes">Cafes</option>
<option value="other">Other</option>
</select>
<div class="category-option makeup">
Div 1
</div>
<div class="category-option makeup">
Div 2
</div>
<div class="category-option makeup">
Div 3
</div>
<div class="category-option other">
Div 4
</div>

Show/hide divs based on values selected in multiple select2 dropdowns

I am building a search result filtering feature. I have a number of select2 dropdown boxes where the user can select multiple values from to either hide or show divs with matching class values. I have a number of divs with classes containing values matching values in the select2 dropdown boxes. How do I go about coding this functionality?
I can only get this to work for one selection, I'd like to be able to select multiple options from the dropdowns.
$('select.filterCandidates').bind('change', function() {
$('select.filterCandidates').attr('disabled', 'disabled');
$('#candidates').find('.row').hide();
var critriaAttribute = '';
$('select.filterCandidates').each(function() {
if ($(this).val() != '0') {
critriaAttribute += '[data-' + $(this).data('attribute') + '*="' + $(this).val() + '"]';
}
});
$('#candidates').find('.row' + critriaAttribute).show();
$('#filterCount').html('Showing ' + $('div#candidates div.row:visible').length + ' Matches');
$('select.filterCandidates').removeAttr('disabled');
});
$('#reset-filters').on("click", function() {
$('#candidates').find('.row').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-12">
<br>
<h4>Search Form</h4>
<br>
</div>
<div class="col-md-4">
<div class="form-group">
<select id="type" class="form-control filterCandidates" data-attribute="type">
<option value="0">Candidate Type</option>
<option value="CA">CA</option>
<option value="CFA">CFA</option>
<option value="CFO">CFO</option>
<option value="CIMA">CIMA</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<select id="role" class="form-control filterCandidates" data-attribute="role">
<option value="0">Preferred Role</option>
<option value="Analyst">Analyst</option>
<option value="Associate">Associate</option>
<option value="CFO">CFO</option>
<option value="FD">FD</option>
<option value="FM">FM</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<select id="roleType" class="form-control filterCandidates" data-attribute="roleType">
<option value="0">Preferred Role Type</option>
<option value="Permanent">Permanent</option>
<option value="Contract/Interim">Contract/Interim</option>
<option value="Internship">Internship</option>
</select>
</div>
</div>
</div>
just to give you a rough idea as you have not provided any code.
<script>
var SelectedValues = $('#ddlSelect option:selected');
var NotSelectedValues $('#ddlSelect option:not(:selected)');
$(SelectedValues ).each(function () {
$("."+$(this).val()+"").show(); //show all those divs containing
//this class
});
$(NotSelectedValues ).each(function () {
$("."+$(this).val()+"").hide();//hide all those divs containing
//this class
});
</script>
This is a rough idea , The above script will show all of the divs containing the classes you have selected in your select2 with id "ddlSelect" and hide those which you have not selected.
you can put this into a function and call it on onchange event of ddlSelect or whatever and however you want it to.

Hide option in select with div

Is it possible to hide a option in select with div, and then use style.display = "none"
Html code I have used:
<div class="test">
<div class="optioncheck" id="text place">
<select id="status" onChange="myFunction()">
<option value="1">Texts</option>
<div class="options" id="text"><option value="2">Text</option></div>
<div class="options" id="text1"><option value="3">Text1</option></div>
</select>
</div>
<div class="optioncheck" id="map" style="display:none;">
Text
<div class="optioncheck" id="map1" style="display:none;">
Text
</div>
</div>
</div>
Javascript I try to use to hide the options if variable is false
var readtext = false;
if (readtext == true) {
document.getElementById('text').style.display = "block";
} else {
document.getElementById('text').style.display = "none";
}
You can't directly. Instead, you have to use (or write) javascript library which will demonstrate divs for select options. Just like Select2 jQuery library does.
You can't use display:none for hiding options in select, if you want to hide option you can use something like
$( "#status option[value=1]" ).wrap( "<span>" );
and to again show the particular option use
if ( $( "#status option[value=2]" ).parent().is( "span" ) ){
$( "#status option[value=2]" ).unwrap();
}
This should do the work for you.
Remove divs, use just options.
Here your code without divs.
http://codepen.io/anon/pen/ryOeWo
<div class="test">
<div class="optioncheck" id="text place">
<select id="status" onChange="myFunction()">
<option value="1">Texts </option>
<option id="text" value="2">Text</option>
<option value="3">Text1</option>
</select>
</div>
<div class="optioncheck" id="map" style="display:none;">
Text
<div class="optioncheck" id="map1" style="display:none;">
Text
</div>
</div>
If you just wish to hide some options other than the first option.You can do that via simple javascript.
Refer to this fiddle:
https://jsfiddle.net/ysd8w8sk/
Let's say we have following html:
<select id="fruits_dropdown">
<option value='1' > Apple </option>
<option value ='2'> Banana </option>
<option value ='3'> Orange </option>
<option value ='4'> Cherry </option>
</select>
Then we can hide option 2 and 3 like this :
document.querySelector('#fruits_dropdown option[ value="2"]').style.display='None';
document.querySelector('#fruits_dropdown option[ value="3"]').style.display='None';

Hide parent element

Here is my HTML;
<div class="pagination__page" data-pagination-page="" data-pagination-group="group-0" style="display: block;">
<div class="question">
<h2 class="question__title">Country</h2>
<div class="form-field form-field--dropdown">
<select required="1" name="country" data-parsley-group="group-0">
<option selected="selected" value="">Please select...</option>
<option value="great-britain">Great Britain</option>
<option value="zimbabwe">Zimbabwe</option>
</select>
</div>
</div>
<div class="question"> // line 13
<h2 class="question__title">Postcode</h2>
<div class="form-field">
<input data-parsley-postcode="1" name="postcode" type="text" data-parsley-group="group-0">
</div>
</div>
</div>
How can I hide the div starting on "line 13" (see comment in code) unless the Country question above's input is Great Britain?
It's dynamic so I can't assign the div directly to give it a name. All I have to go on is the input which has name of postcode.
If I could access that div, then I think it would be something like;
$('#country').on('change.postcode', function() {
$("#").toggle($(this).val() == 'great-britain');
}).trigger('change.postcode');
There is a function in JQuery called parent(). You can use get the input node via
$("input[name='postcode']")
and then access the parent of it's parent to hide it like that:
$("input[name='postcode']").parent().parent().hide();
Learn more about parent() here.
EDIT (thanks to andlrc):
You could also use closest() instead of the double parent():
$("input[name='postcode']").closest("div.question").hide();
see here.
A combination of parent and next should do the trick:
$(function(){
$('select[name="country"]').change(function(){
var country = $(this).val();
if(country == 'great-britain'){
$(this).parent().parent().next('.question').show();
}
else{
$(this).parent().parent().next('.question').hide();
}
});
});
In order to hide the dinamically generated html, you can do something like this:
$('.question').each(function(i,item){
if((i+1) % 2 ==0){
$(item).hide();
}
});
Updated fiddle: https://jsfiddle.net/robertrozas/pen942nf/1/
You This must work:
<style>
.hide{display:none;}
</style>
<div class="pagination__page" data-pagination-page="" data-pagination-group="group-0" style="display: block;">
<div class="question">
<h2 class="question__title">Country</h2>
<div class="form-field form-field--dropdown">
<select required="1" name="country" data-parsley-group="group-0">
<option selected="selected" value="">Please select...</option>
<option value="great-britain">Great Britain</option>
<option value="zimbabwe">Zimbabwe</option>
</select>
</div>
</div>
<div class="question sh"> // line 13
<h2 class="question__title">Postcode</h2>
<div class="form-field">
<input data-parsley-postcode="1" name="postcode" type="text" data-parsley-group="group-0">
</div>
</div>
</div>
<script>
$("#country").change(function(){
$(this).find("option:selected").each(function(){
if($(this).attr("value")=="great-britain"){
$('.sh').show();
}
else{
$('.sh').hide();
});
});
</script>

jQuery - Controlling div visibility with a Select Box

Updated: I would like to control the visibility of the bottom divs based on the value of the top SELECT..
i.e
selected = dogs:: only bulldog, pitbull visible
selected = fish:: GOLDFISH! visible
etc..
Appreciate it.. Sorry I didn't do a better job of explaining my question initially -
<select>
<option value="dog">dog</option>
<option value="cat">cat</option>
<option value="fish">fish</option>
</select>
<div id="dog">bulldog</div>
<div id="cat">stray cat</div>
<div id="dog">pitbull</div>
<div id="cat">alley cat</div>
<div id="fish">GOLDFISH!</div>
Try this
$('#pets').change(function() {
$('#somepets div').hide();
$('#somepets div.' + $(this).val()).show();
});
But for this you should change your class names to match the values of the options. Also you need to give your "select" element an ID.
EDIT: To clarify a bit, this selector is going to try and find the select element by its ID "pets" so you need to add id="pets". The name and ID can be the same value.
EDIT: Since you're having some trouble with the HTML here is what it would need to look like to work with my method.
<select id="pets">
<option value="dog">dog</option>
<option value="cat">cat</option>
<option value="fish">fish</option>
</select>
<div id="somepets">
<div class="dog">bulldog</div>
<div class="cat">stray cat</div>
<div class="dog">pitbull</div>
<div class="cat">alley cat</div>
<div class="fish">GOLDFISH!</div>
</div>
<script type="text/javascript" src="jquery-1.6.2.js"></script>
<script type="text/javascript">
function selectionChanged(){
HideAll();
var selected=$('#pets option:selected').text();
var selectString='.';
selectString+=selected;
$(selectString).show();
};
function HideAll(){
$('.dog').hide();
$('.cat').hide();
$('.fish').hide();
};
</script>
<select id="pets" onchange="selectionChanged()">
<option>dog</option>
<option>cat</option>
<option>fish</option>
</select>
<div id=somepets>
<div class="dog">bulldog</div>
<div class="cat">stray cat</div>
<div class="dog">pitbull</div>
<div class="cat">alley cat</div>
<div class="fish">GOLDFISH!</div>
</div>

Categories

Resources