only one value is equal to and selected in multiple select - javascript

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>

Related

Dropdown selections jQuery

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.

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>

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.

How to add action in HTML depending on two option combination?

How to add condition like this:
If customer chose Japan as a pickup option and England as a dropoff option, page sends him on page with prices of that destination and for some other input there is exactly one output for exact chosen destination and pickup place.
<div class="advanced-search color" id="booking">
<div class="wrap">
<form role="form" action="index.html" method="get">
<!-- Row -->
<div class="f-row">
<div class="form-group select one-third">
<label>Pick up location</label>
<select id="pickup1" name="p1">
<option value="">Select pickup location</option>
<optgroup label="Asia">
<option value="1">China</option>
<option value="2">Japan</option</optgroup>
</select>
</div>
<div class="form-group select one-third">
<label>Drop off location</label>
<select id="dropoff1" name="d1">
<option value="">Select drop-off location</option>
<optgroup label="Europe">
<option value="3">England</option>
<option value="4">Spain</option</optgroup>
</select>
</div>
<div class="form-group right">
<center>
<label>Check for informations</label>
</center>
<button type="submit" class="btn large black">Find a transfer</button>
</div>
</div>
<!-- //Row -->
</form>
</div>
</div>
You can use jquery for this,
$(#dropOffSelect).on('change',function(){
var dropOffval = $(this).val();
var pickUplocation = $('#pickUpselect').val();
//condition runs here
if(pickUplocation ==='Japan' && dropOffval === 'Europe'){
// show the information for it
}
})
This is simple using jQuery. You send the values to the pricelist page via querystring in your url. On load of the pricelist page you get the values from the query string and filter based on it.
Now you'll have to work with the values in the list and not the text. You can match the values from a database or you can still use the country name as the value.
$(function() {
$('#btnSubmit').click(function() {
$('form').attr('action', 'pricelist?pickup=' + p1.val() + '&dropoff=' + d1.val());
$('form').submit();
});
you can use window.location within your script no need to use action just add onclick="Myfunc()" event.
if(pickup == "japan" && dropoff == "england")
window.location = "url";

Bootstrap Select Menu - Add New Option

I have a simple Bootstrap form with a select input:
<div class="form-group">
<label for="category" class="control-label col-sm-3">Category</label>
<div class="input-group col-xs-8">
<select class="form-control" name="category" id="category">
<option value="Fruit">Fruit</option>
<option value="Vegetables">Vegetables</option>
</select>
</div>
</div>
The users now have a requirement to be able to add a new option dynamically to the select menu rather than be restricted to the items on the select menu.
I'm not sure if it's possible to modify a select menu and how to make it consistent with the rest of the Bootstrap framework?
To add an option dynamically, there should be a UI button giving you that choice. To get user input, we can use the window.prompt method.
We then create an option element, set its value attribute and set its name. Then just append these elements and nodes to the DOM with appendChild
Try playing around with this. I added some items like Steak, potatoes and beer.
var addOption = document.getElementById("add-option");
var selectField = document.getElementById("category");
addOption.addEventListener("click", function() {
var item = prompt("What would you like");
var option = document.createElement("option");
option.setAttribute("value", item);
var optionName = document.createTextNode(item);
option.appendChild(optionName);
selectField.appendChild(option);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="form-group">
<label for="category" class="control-label col-sm-3">Category</label>
<div class="input-group col-xs-8">
<select class="form-control" name="category" id="category">
<option value="Fruit">Fruit</option>
<option value="Vegetables">Vegetables</option>
</select>
</div>
</div>
<button id="add-option" class="btn btn-primary">Add a new option</button>
You mean something like this?
some select
<select id="region" class="selectpicker">
<option>region 1</option>
<option>region 2</option>
<option>region 3</option>
</select>
jquery js
$('.selectpicker').selectpicker();
$("#region").on('change', function () {
$(this)
.append('<option>region4</option><option>region5</option>')
.selectpicker('refresh');
});

Categories

Resources