Dropdown selections jQuery - javascript

I am making a dropdown and want to show the div class="residential-options" when the id="residential" is selected and show the div class="commercial-options" when the id="commercial" is selected.
heres my HTML:
<div class= "row">
<select id='building-type'>
<option disabled selected value> -- select an option -- </option>
<option id="residential" value="residential" [...]>Residential</option>
<option id="commercial" value="commercial " [...]>Commercial</option>
<option id="corporate" value="corporate" [...]>Corporate</option>
<option id="hybrid" value="hybrid" [...]>Hybrid</option>
</select>
</div>
<div class="residential-options">
<div id="number-of-apartments" >
<label>N. of Apartments *</label>
<input [...]>
</div>
<div id="number-of-basements" >
<label>N. of Basements *</label>
<input [...]>
</div>
</div>
<div class="commercial-options">
<div id="number-of-floors" >
<label>N. of Floors *</label>
<input [...]>
</div>
heres my jQuery:
$("#building-type").change(function() {
($('#residential').is(':checked'))
$('.residential-options').show();
$('.commercial-options').hide();
$('.corporate-options').hide();
$('.hybrid-options').hide()
});
$("#building-type").trigger("change");
$("#building-type").change(function() {
($('#commercial').is(':checked'))
$('.commercial-options').show();
$('.residential-options').hide();
$('.corporate-options').hide();
$('.hybrid-options').hide()
});
$("#building-type").trigger("change");
it only shows the div class="commercial-options" whatever I click on. Thanks for your help!

Your code can be simplified greatly, including removing the .trigger() calls.
$("#building-type").change(function() {
$('div[class*="options"]').hide(); // hide all '*-option' divs
// Determine which option was selected and display the corresponding div:
['residential', 'commercial', 'corporate', 'hybrid'].forEach(function(base){
if ($('#' + base + ':checked').length) {
$(`.${base}-options`).show();
}
})
})

you can change your code to something like this:-
get the selected value from the building type .
compare the value using if, else if statements and inside if / else if statements show and hide your div's using class attribute.

Related

Trying to clear a select

I have two dropdowns (select in HTML), when I select the option in the first dropdown it has to fill the second according to the id of the selected item of the first. It's doing well at removing all the previous options and filling with the id selected in the first dropdown, however it's not removing the text appearing as selected. I'm stuck at the version 1.11 of Jquery if it matters somehow. I've tried doing this both through Jquery and Javascript.
Here is the html code where the selects are:
<div class="ui-grid-a">
<div class="ui-block-a uf">
<label for="cpEstado" class="select">
<select name="estado" id="cpEstado" data-theme="c"> <!--onchange="appUsuario.buscarCidades( this.value );">-->
<option value="" disabled selected>UF</option>
</select>
</label>
</div>
<div class="ui-block-b cidade">
<label for="cpCidade" class="select">
<select name="cidade" id="cpCidade" data-theme="c">
<option value="1" disabled selected>Cidade</option>
</select>
</label>
</div>
Here is the Jquery function I used to fill the second dropdown:
$(document).on('change', '#cpEstado', function() {
$('#cpCidade').empty();
appUsuario.buscarCidades( this.value );});
When I changed the text of the selected text,
$("#cpCidade option:selected").html('Mudança de valor');
This happened. It changes the text of the item in the dropdown but not in the selected item:
You should be setting the value of the second dropdown (instead of setting the html content of the selected option):
$("#cpCidade").val('{id}');
Where id = the value of 'Mudança de valor'

How can I add more elements inside jquery.sumoselect plugin select list?

I want to add more elements inside a list with multiple select checkboxes, but when I add more elements, they appear outside the list.
This is the code I want to put in:
<div class="select-box-style right">
<div class="your-list-title">Your Lists</div>
<select multiple="multiple" class="md_what_get right SlectBox">
<option selected value="electronics">Electronics</option>
<option value="games">Video Games</option>
<option value="books">Books</option>
<option value="others">Others</option>
</select>
<div class="add-list-box">
<input type="text" class="input-add-list" />
<label class="label-spcbtn-blue spr">Add</label>
</div>
</div>
I want the select option to be displayed like this:
As per your comments if you want to put it inside list you can do it as below:
Put it as first element:
DEMO
$('.spr').on('click',function(){
if($('.input-add-list').val().trim()!=='')
{
$('<option value="'+$('.input-add-list').val().trim()+'">'+$('.input-add-list').val().trim()+'</option>').insertBefore('.SlectBox option:first');
}
});
Put it as last element
DEMO
$('.spr').on('click',function(){
if($('.input-add-list').val().trim()!=='')
{
$('.SlectBox').append('<option value="'+$('.input-add-list').val().trim()+'">'+$('.input-add-list').val().trim()+'</option>');
}
});
If possible change your label Add to button
Update
Use your native plugin method as below:
DEMO
$('.spr').on('click',function(){
if($('.input-add-list').val().trim()!=='')
{
$('select.SlectBox')[0].sumo.add($('.input-add-list').val().trim());
}
});

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>

How To Refactor This Repeating jQuery Code

I have a page with about 40 checkboxes and selects (all dynamically built by web app code) that I would like to use the following (working) piece of jQuery for. What I don't want to do is have to repeat this code for each and every checkbox, etc. I am not sure what the best way to approach this would be, as I am not a JavaScript/jQuery expert.
Does anyone have a suggestion for how the following code could be refactored to use with an arbitrary number of checkboxes and selects. The goal is to query a database and build the list of checkboxes and selects from it.
EDIT: This code needs to fire for the individual checkbox and its hidden select, as opposed to all of the checkboxes -- sorry I did not make that clear from the original post :)
$('#ssp_checkbox').change (function() {
$('#ssp_container').fadeIn();
});
$('#ssp_select').change(function() {
$('#ssp_addon').fadeIn().html('<i class="icon-ok"></i> ' + $('#ssp_select').val() + ' SSPs Ordered ' + '<button type="button" id="ssp_remove" class="btn btn-mini btn-danger">Remove</button>');
$('#ssp_container').fadeOut();
})
$(document).on('click', '#ssp_remove', function(){
$('#ssp_select').val('0');
$('#addons').find('#ssp_addon').fadeOut('slow');
$('#ssp_checkbox').attr('checked', false);
countChecked();
})
EDIT:
This is the snippet of HTML -- there are about 40 of these, and they are have different IDs, but are otherwise the same:
<!-- Civil Search / ServCode Prefix: civil / FIELDS: civil_checkbox, civil_select -->
<div class="row-fluid">
<div class="span12">
<!-- civil -->
<label class="checkbox">Civil Search
<input type="checkbox" class="" name="civil_checkbox" id="civil_checkbox">
</label>
</div><!--/Civil Search Span -->
</div><!--/Civil Search Row -->
<!-- Civil Search Select / FIELDS: civil_select -->
<div class="row-fluid addon-select-container" id="civil_select-container">
<div class="span12">
<!-- civil_select -->
<label for="">Number of Services to Add:</label>
<select class="span2" name="civil_select" id="civil_select">
<option value="0" selected>0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div><!--/Civil Search Addon Select Span -->
</div><!--/Civil Search Addon Select Row -->
Thanks!
I don't know exactly what your code needs to do, but I "think" I have a general idea of what you're going for.
I threw something together in a fiddle (below is the code). What it's doing is adding a data attribute to the input:checkbox elements with the div associated to the checkbox. Then it triggers a switch to show/hide the div tags. This will run across an unlimited number of checkboxes.
<!-- here are the 40 checkboxes, truncated for brevity -->
<label for="cb1">Check One</label>
<input type="checkbox" name="cb1" id="cb1" data-associated-div="a">
<label for="cb2">Check Two</label>
<input type="checkbox" name="cb2" id="cb2" data-associated-div="b">
<label for="cb3">Check Three</label>
<input type="checkbox" name="cb3" id="cb3" data-associated-div="c">
<!-- pretend these are big, convoluted drop down's -->
<div id="a" class="hidden">alpha</div>
<div id="b" class="hidden">bravo</div>
<div id="c" class="hidden">charlie</div>
$('body').ready(function(){
// hide all hidden elements by default
$('.hidden').hide();
});
$('input:checkbox').change(function () {
// get the target div from the data attribute 'associatedDiv'
var targetDiv = '#' + $(this).data('associatedDiv');
// if it's hidden, show it
if ($(targetDiv).is(":hidden")) {
$(targetDiv).fadeIn();
// if it's visible, hide it
} else {
$(targetDiv).fadeOut();
}
});
Instead of $('#ssp_checkbox')...
If you want all checkboxes then just select them all
$('input:checkbox')
or give each checkbox a class, e.g. 'mycheckbox' and use that..
$('.mycheckbox')
Same for the Selects.
$('select')
http://api.jquery.com/category/selectors/

'fadeToggle' multiple div tags via drop down menu

I need to be able to hide/show multiple div tags on the same page via a drop down menu, but I want them to use the jQuery 'fadeToggle'. I can easily do this without 'fadeToggle' by using the following code:
function generateTask() {
document.getElementById('football').style.display = 'none';
document.getElementById('football2').style.display = 'none';
}
html:
<select name="something" id="something">
<option value="1" onclick="generateTask();">Football</option>
<option value="2" onclick="generateTask();">Cricket</option>
<option value="3" onclick="generateTask();">Baseball</option>
</select>
<div id="football">balls</div>
<div id="football2">shorts</div>
But this solution isn't as elegant. Any help would be appreciated.
The main complication is that the div tags "football" and "football2" might both be required for Cricket but only "football2" required for say Baseball.
You can try this
function generateTask(){ $('#football, #football2').toggle();}
Or yan can add classes on every elements that should be affected by your dropdown:
For example:
<div id="football" class="football">balls</div>
<div id="football2" class="football cricket">shorts</div>
<div id="cricket" class="cricket">stick</div>
And than target every element that's in link with your dropdown action.
If you can keep the value of the options as the ids of the divs then it will be much simpler.
Something like this
Markup
<select name="something" id="something">
<option value="football">Football</option>
<option value="cricket">Cricket</option>
<option value="baseball">Baseball</option>
</select>
<div id="football" class="content">Football content</div>
<div id="cricket" class="content">Cricket content</div>
<div id="baseball" class="content">Baseball content</div>
JS
$("#something").change(function(){
var id = "#"+this.value;
//This will hide all the divs with class content but not the selected option
$(".content").filter(":not("+id+")").hide();
$(id).fadeToggle();//This will toggle div based on the selected option
});

Categories

Resources