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

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.

Related

How to trigger dynamic dropdown in Edit View

I am new to web development and I just learned Jquery to create dynamic dropdowns. The problem that I am facing is that my dropdowns are not being updated when I go to the edit view.
So I have been able to successfully create dynamic dropdowns for my Create view (see code).
Create.cshtml:
<div class="form-group col-md-4" id="drop_1">
<label asp-for="Option_1" class="control-label"></label>
<select asp-for="Option_1" class="form-control" id="opt1">
<option value="">Select Option</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<span asp-validation-for="Option_1" class="text-danger"></span>
</div>
<div class="form-group col-md-4" id="drop_2">
<label asp-for="Option_2" class="control-label"></label>
<select asp-for="Option_2" class="form-control" id="opt2">
<option value="">Select Option</option>
</select>
<span asp-validation-for="Option_2" class="text-danger"></span>
</div>
<div class="form-group col-md-4" id="drop_3">
<label asp-for="Option_3" class="control-label"></label>
<select asp-for="Option_3" class="form-control" id="opt3">
<option value="">Select Option</option>
</select>
<span asp-validation-for="Option_3" class="text-danger"></span>
</div>
Edit.cshtml is the same as Create.cshtml
Site.js:
$(function() {
$('#opt3').change(function () {
var x = $(this);
if (x.val() == "") {
$('#drop_2').hide();
$('#drop_3').hide();
}
else {
if (x.val() == "A") {
$('#opt2').find('option').remove().end();
$('#opt2').append('<option value="D">D</option>');
.
.
. etc.
}
}
//Same for the remaining dropdowns
});
});
The point is that my dropdowns work when I start clicking on my dropdowns. But what I would like to see is that when I try to go into my edit views and the data is pulled in, the dropdowns automatically get changed based on whatever data there is for dropdown 1 and 2, without the user having to reselect dropdown 1 and 2.
The change event is sent to an element when its value changes. If you want to make the dropdownlist changes when page is loading the first time , you can write your javascript methods directly in $(function () {}); . For example , if you want to add D option to select 2 after loading edit views :
<script>
$(function () {
$('#opt2').append('<option value="D">D</option>');
//write your other logic here
$('#opt3').change(function () {
var x = $(this);
if (x.val() == "") {
$('#drop_2').hide();
$('#drop_3').hide();
}
else {
if (x.val() == "A") {
$('#opt2').find('option').remove().end();
$('#opt2').append('<option value="D">D</option>');
}
}
//Same for the remaining dropdowns
});
});
</script>

populate select box on previous select and with clone

I am trying to add cloning functionality for select boxes.
I have 3 select box: country, state, city and first user select the country and on id basis state select box is populated with options and same with city dropdown will populate only when state is selected.
Then I have add more option where I have regenerate everything. so I am cloning my div but the problem when I change my country instead of showing new state dropdown its returns to previous drop down:
$('.country').on('change',function(){
var id = $(this).val();
callAjax(id);
});
$('.state').on('change',function(){
var id = $(this).val();
callAjax(id);
});
$('#btClone').on('click', function () {
$('#country')
.clone()
.attr('id', 'country_' + i)
.attr('name', 'country_' + i)
.appendTo("#container2");
$('#state')
.clone()
.attr('id', 'state_' + i)
.attr('name', 'state_' + i)
.appendTo("#container2");
i =i+1;
});
My Html looks like
<div id="container1">
<select id="country" name="country" class="hidden country">
</select>
<select id="state" name="state" class="hidden state">
</select>
<select id="city" name="city" class="hidden city">
</select>
<span id="selected-profile"></span>
<div id="addons" class="hidden">
<input type="button" id="btClone" value="Clone the list" style="float:right;" />
</div>
</div>
<div id="container2" style="display:none;"></div>
I want when i click on add new then chose country then change something my ajax call again call but as of now i am unable to do that because i already have options
what exactly do you mean with "instead of showing new state dropdown its returns to previous drop down". I tried your code in a fiddle and it's cloning as expected.
function initRow($row){
$row.find('select[name="country"]').on('change', function () {
var thisRow = $(this).closest('div.row');
var stateDD = thisRow.find($('select[name="state"]'));
stateDD.show();
stateDD.on('change',function(){
var cityDD = thisRow.find('select[name="city"]');
cityDD.show();
cityDD.on('change',function(){
});
});
});
}
$('#container1 .row').each(function(){
initRow($(this));
});
$('#btClone').click(function(){
var rowTemplate = $('#container1 > .row').eq(0).clone();
rowTemplate.find('select[name="state"]').hide();
rowTemplate.find('select[name="city"]').hide();
initRow(rowTemplate.appendTo($('#container1')));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container1">
<div class="row">
<select name="country" class="hidden country">
<option value=1>country 1</option> <option value=2>country 2</option>
</select>
<select name="state" class="hidden state" style="display:none;">
<option value=1>state 1</option> <option value=2>state 2</option>
</select>
<select name="city" class="hidden city" style="display:none;">
<option value=1>city 1</option> <option value=2>city 2</option>
</select>
</div>
</div>
<input type="button" id="btClone" value="Clone the list" style="float:right;" />

disable an option of a dropdown list in selectize.js

I use selectize.js for dropdown lists in my project. I have 3 dropdown lists related to each other. When I click an option from first dropdown list, some elements from second and third dropdown lists should be disabled. When I click an option from second dropdown list, some elements from third dropdown list should be disabled.
When I try some basic jquery or javascript methods to disable an option from dropdownlists, they don't affect. However, when I delete selectize.js classes from dropdownlists, they immediately affect, disable options that I want.
Here is my sample code for dropdownlists;
<div id="pro_yur_gru" class="row form-row">
<div class="col-lg-4 col-md-4">
<label class="form-label">Person</label>
<select id="Person1" class="demo-default" name="PERSONLIST" onchange="my_onchange_function_to_remove_2_and_3()">
<option value="">Select a person...</option>
<option value="4">Albert</option>
<option value="1">Frank</option>
<option value="3">Doug</option>
<option value="5">Arnold</option>
</select>
<script type="text/javascript">
$('#Person1').selectize({
allowEmptyOption:true,
create: true,
dropdownParent: 'body'
});
</script>
</div>
</div>
<div id="pro_yur_gru2" class="row form-row">
<div class="col-lg-4 col-md-4">
<label class="form-label">Person 2</label>
<select id="Person2" class="demo-default" name="PERSONLIST2" onchange="my_onchange_function_to_remove_3()">
<option value="">Select a person...</option>
<option value="4">Thomas</option>
<option value="1">Mark</option>
<option value="3">Nicholas</option>
<option value="5">James</option>
<option value="6">Matt</option>
<option value="7">Kenny</option>
</select>
<script type="text/javascript">
$('#Person2').selectize({
allowEmptyOption:true,
create: true,
dropdownParent: 'body'
});
</script>
</div>
</div>
<div id="pro_yur_gru_3" class="row form-row">
<div class="col-lg-4 col-md-4">
<label class="form-label">Person3</label>
<select id="Person3" class="demo-default" name="PERSONLIST3">
<option value="">Select a person...</option>
<option value="1">Chuck</option>
<option value="3">Alex</option>
<option value="2">Donald</option>
<option value="5">John</option>
<option value="7">Dwayne</option>
<option value="6">Kevin</option>
<option value="4">Tim</option>
<option value="8">Patrick</option>
</select>
<script type="text/javascript">
$('#Person3').selectize({
allowEmptyOption:true,
create: true,
dropdownParent: 'body'
});
</script>
</div>
</div>
What I need is something like this;
to change <option value="4">Albert</option> to <option disabled value="4">Albert</option> by using a javascript function.
Edit: I use this project on IE10.
Disabled select options can also be achieved by overriding the render function.
$('#control').selectize({
render: {
option: function(item, escape) {
if (item.value === '') {
return '<div style="pointer-events: none; color: #aaa;">' + escape(item.label) + '</div>';
}
return '<div>' + escape(item.label) + '</div>';
}
}
});
Or uses plugin https://github.com/mondorobot/selectize-disable-options

Disabling select input depending on previous select option

What I'm trying to achieve here is this: I have a select input that has 3 options : Sale, Rent, Wanted. Depending on which option is selected, there are 3 other select inputs. So lets say I choose Sale then it should show the property sale select input and hide the other two, if I choose Rent then it should show the property rent select input and the hide the other two.
The hiding works well but my issue is when i submit for search using GET, it passes the data of the two other hidden select inputs because they are not disabled. I tried disabling them depending on selection as shown in the below code but it didn't work. Any help?
Here is my code:
<script type="text/javascript">
$('#type').on('change',function(){
if( $(this).val() === "sale"){
$("#propertyrent").hide();
$("#propertywanted").hide();
$("#pricetype").show();
$("#propertysale").show();
document.getElementById("propertyrent").disabled=true;
document.getElementById("propertywanted").disabled=true;
}
else if( $(this).val() === "rent"){
$("#pricetype").hide();
$("#propertyrent").show();
$("#propertywanted").hide();
$("#propertysale").hide();
document.getElementById('propertysale').disabled=true;
document.getElementById('propertywanted').disabled=true;
}
else if( $(this).val() === "wanted"){
$("#pricetype").hide();
$("#propertyrent").hide();
$("#propertywanted").show();
$("#propertysale").hide();
document.getElementById('propertyrent').disabled=true;
document.getElementById('propertysale').disabled=true;
}
});
</script>
<label class="col-sm-3 control-label">Type</label>
<select name="type" id="type">
<option value="sale">Sale</option>
<option value="rent">Rent</option>
<option value="wanted">Wanted</option>
</select>
<div id="propertysale">
<label class="col-sm-3 control-label">Property</label>
<select name="propertysale" id="propertysale" class="form-control col-sm-12">
<option value="all">Any</option>
<option value="houses">Houses</option>
<option value="apartments">Apartments</option>
<option value="land">Land</option>
<option value="buildings">Buildings</option>
<option value="wfsc" >Warehouse / Factory / Store / Chalet</option>
</select>
</div>
<div id="propertyrent" style="display:none;">
<label class="col-sm-3 control-label">Property</label>
<select name="propertyrent" id="propertyrent" class="form-control col-sm-12">
<option value="all">Any</option>
<option value="houses">Houses</option>
<option value="apartments">Apartments / Flats</option>
<option value="wfsc" >Warehouse / Factory / Store / Chalet</option>
</select>
</div>
<div id="propertywanted" style="display:none;">
<label class="col-sm-3 control-label">Property</label>
<select name="propertywanted" id="propertywanted" class="form-control col-sm-12">
<option value="all">Any</option>
<option value="houses">Houses</option>
<option value="apartments">Apartments</option>
<option value="land">Land</option>
<option value="buildings">Buildings</option>
<option value="wfsc" >Warehouse / Factory / Store / Chalet</option>
</select>
Use jQuery selector for any input inside div to disabling them:
$("#yourDiv input, #yourDiv select").prop("disabled", true);
To remove disabled: prop("disabled", false);
here div and your selectbox id is same 'propertyrent','propertywanted','propertysale' change this.
and when you hide or disable selectbox set value blank of select box
The problem is, you are not disabling the select menu. You are disabling the div that contains the select menu
<div id="propertyrent" style="display:none;">..
<select name="propertyrent" id="propertyrent" c...
Use different id for both. It will work

only one value is equal to and selected in multiple select

I have the exact same question as this:
jQuery Hide / Show input when selected option is equal to
However, it doesn't work when you go to multiple select, when the specific option is selected it works, but when you select another option alongside it stops working.
The question again is this: I want to show a div(#showme) if option 4 was selected, and I want to to work even if option 3 & 4 were selected, so at any given time if option 4 was selected the div should show.
This is the Javascript & HTML I have so far: (please note that I have more than one select in this form)
$('select[multiple]').each(function() {
$(this).change(function() {
obj = '#' + $(this).attr('id') + '_desc';
if($(this).val() == "4") {
$(obj).parent().parent().parent().removeClass('hide');
$(obj).css('display','block');
}
else {
$(obj).parent().parent().parent().addClass('hide');
$(obj).css('display','none');
}
});
});
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="feedback_q1">Hello?</label>
<select class="form-control selectpicker show-tick" name="feedback_q1[]" id="feedback_q1" multiple="multiple" title="Choose...">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
</div>
</div>
<div class="row hide">
<div class="col-sm-12">
<div class="form-group">
<label for="feedback_q1_desc">desc <span class="glyphicon glyphicon-pencil"></span></label>
<textarea name="feedback_q1_desc" id="feedback_q1_desc" class="form-control" data-toggle="tooltip" data-placement="top" title="desc" rows="2"></textarea>
</div>
</div>
</div>
Thanks for the help
When multiple selections are made, $(this).val() will contain an array of the values. Iterate through them and check for '4'. If $(this).val() is null, then nothing has been selected.
The example below does exactly what you want, including the changes after our extensive exchange in the comments and chat, including your most recent request to handle values pre-selected when the document loads.
Additionally, you were missing the bootstrap JavaScript file, and the files you were already including were in the wrong order and wrong location. The example below includes all of the .js and .css files in the correct order and location.
HTML
<!-- These should be in head -->
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.min.css" rel="stylesheet" />
<!-- Body content -->
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="feedback_q1">Hello?</label>
<select class="form-control selectpicker show-tick" name="feedback_q1[]" id="feedback_q1" multiple="multiple" title="Choose...">
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3">3</option>
<option value="4" selected>4</option>
</select>
</div>
</div>
</div>
<div class="row hide">
<div class="col-sm-12">
<div class="form-group">
<label for="feedback_q1_desc">desc <span class="glyphicon glyphicon-pencil"></span>
</label>
<textarea name="feedback_q1_desc" id="feedback_q1_desc" class="form-control" data-toggle="tooltip" data-placement="top" title="אנא פרט" rows="2"></textarea>
</div>
</div>
</div>
<!-- These should be at the end of <body> -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.min.js"></script>
JavaScript
// Check a select for a specific value and show/hide div based on selection
// Select will come in as a jQuery object
function checkSelect(control) {
// Build selector for associated description field
var selector = '#' + control.attr('id') + '_desc';
// Handle scenario where nothing is selected
if (control.val() == null) {
$(selector).parent().parent().parent().addClass('hide');
$(selector).css('display', 'none');
return;
}
// Get array containing selected values
var vals = control.val();
// Handle scenario where something is selected
for (i = 0; i < vals.length; i++) {
if (control.val()[i] == "4") {
$(selector).parent().parent().parent().removeClass('hide');
$(selector).css('display', 'block');
return; // Stop checking as we know the value we want is selected
} else {
$(selector).parent().parent().parent().addClass('hide');
$(selector).css('display', 'none');
}
}
}
// This runs when the DOM is ready
$(function () {
// Bind selectpicker
$('.selectpicker').selectpicker();
// Iterate through all multiple selects
$('select[multiple]').each(function () {
// Check for pre-selected values when page first loads
checkSelect($(this));
// Bind to change event so that values are checked after something is changed
$(this).change(function () {
checkSelect($(this));
});
});
});
Demo (third version): http://jsfiddle.net/BenjaminRay/7ckp7epf/
<div class="form-group">
<select class="form-control selectpicker show-tick" name="Status" id="Status" multiple="multiple" title="Choose...">
#foreach (SelectListItem item in ViewBag.Status)
{
if (item.Selected == false)
{
<option value="#item.Value">#item.Text</option>
}
else
{
<option value="#item.Value" selected>#item.Text</option>
}
}
</select>
</div>

Categories

Resources