How to display content depending on dropdown menue user selection - javascript

I have a dropdown menu at the bottom of a form with 6 different options.
I need to display different content on a div below this menu depending on which option is selected.
No additional content should be visible until the user is to select one of the options and once the user select one of the options only content associated with that specific option should be visible.
I need to create this functionality using JavaScript but my knowledge of JavaScript is very limited and I don’t seem to find what I need online.
I believe what I need to do is create 6 different divs(one for each option) and toggle
a class that makes them visilble once its respective title is selected.
Here is the dropdown menu that I have:
<div class="field">
<label for="roleBox" data-label="I_AM">{% trans %} main.I_AM_TITLE {% endtrans %}</label>
<div class="f-wrapper">
<select class="cbx" tabindex="50" name="role">
<option value="student">A Student</option>
<option value="educator">An Educator</option>
<option value="parent">A parent signing up for my child</option>
<option value="not-school">Not in school but still learning</option>
<option value="publisher">A Publisher or interested Kno partner</option>
</select>
</div>
</div>
Any help will be greatly appreciated.

I added the divs you mentioned and gave each an id which makes the Javascript a little easier.
Javascript
var ids=["student", "educator", "parent", "not-school", "publisher"];
var dropDown = document.getElementById("roleSel");
dropDown.onchange = function(){
for(var x = 0; x < ids.length; x++){
document.getElementById(ids[x]).style.display="none";
}
document.getElementById(this.value).style.display = "block";
}
HTML
<div class="field">
<label for="roleBox" data-label="I_AM">{% trans %} main.I_AM_TITLE {% endtrans %}</label>
<div class="f-wrapper">
<select id="roleSel" class="cbx" tabindex="50" name="role">
<option value="student">A Student</option>
<option value="educator">An Educator</option>
<option value="parent">A parent signing up for my child</option>
<option value="not-school">Not in school but still learning</option>
<option value="publisher">A Publisher or interested Kno partner</option>
</select>
</div>
</div>
<div id="student" class="hidden">Student div</div>
<div id="educator" class="hidden">Educator div</div>
<div id="parent" class="hidden">Student div</div>
<div id="not-school" class="hidden">Not School div</div>
<div id="publisher" class="hidden">Student div</div>
Working Example http://jsfiddle.net/qbzmz/

use the onchange function like so
<div class="field">
<label for="roleBox" data-label="I_AM">{% trans %} main.I_AM_TITLE {% endtrans %}</label>
<div class="f-wrapper">
<select class="cbx" id="selctor" tabindex="50" name="role" onchange="selectChanged();">
<option value="student">A Student</option>
<option value="educator">An Educator</option>
<option value="parent">A parent signing up for my child</option>
<option value="not-school">Not in school but still learning</option>
<option value="publisher">A Publisher or interested Kno partner</option>
</select>
</div>
</div>
<script>
function selectChanged(){
//get the value of selector and act upon it
//i would use jquery to do this stuff
}
</script>

Related

Bootstrap dropdown won't close on choosing an option

I have a dropdown list that has a nice select using bootstrap 3.4.1.
The issue that i have is that: the drop down remain open after select and never close unless i click outside the list.
HTML code:
<div id="countrysd" class="row option-box">
<div class="option-box-header">
<h3 style="color:#164680">Number <span style="color:#C32952">of Users</span> </h3>
<p>Select the users country and move the range slider to set how many users </p>
</div>
<div class="col-md-6 col-sm-6">
<input type="hidden" id="option100Title" name="option100Title" value="Select" />
<input type="hidden" id="option100Price" name="option100Price" value="0" />
<select id="countryList" class="wide price-list" name="countryList" onchange="showChange()">
<option value="">Select</option>
<option value="egypt">Egypt User</option>
<option value="uae">UAE User</option>
<option value="usa">USA User</option>
</select>
</div>
</div>
JavaScript code that casuing the issue
!function(e){e.fn.niceSelect=function(t){function s(t){t.after(e("<div></div>").addClass("nice-select").addClass(t.attr("class")||"").addClass(t.attr("disabled")?"disabled":"").attr("tabindex",t.attr("disabled")?null:"0").html('<span class="current"></span><ul class="list"></ul>'));var s=t.next(),n=t.find("option"),i=t.find("option:selected");s.find(".current").html(i.data("display")||i.text()),n.each(function(t){var n=e(this),i=n.data("display");s.find("ul").append(e("<li></li>").attr("data-value",n.val()).attr("data-display",i||null).addClass("option"+(n.is(":selected")?" selected":"")+(n.is(":disabled")?" disabled":"")).html(n.text()))})}if("string"==typeof t)return"update"==t?this.each(function(){var t=e(this),n=e(this).next(".nice-select"),i=n.hasClass("open");n.length&&(n.remove(),s(t),i&&t.next().trigger("click"))}):"destroy"==t?(this.each(function(){var t=e(this),s=e(this).next(".nice-select");s.length&&(s.remove(),t.css("display",""))}),0==e(".nice-select").length&&e(document).off(".nice_select")):console.log('Method "'+t+'" does not exist.'),this;this.hide(),this.each(function(){var t=e(this);t.next().hasClass("nice-select")||s(t)}),e(document).off(".nice_select"),e(document).on("click.nice_select",".nice-select",function(t){var s=e(this);e(".nice-select").not(s).removeClass("open"),s.toggleClass("open"),s.hasClass("open")?(s.find(".option"),s.find(".focus").removeClass("focus"),s.find(".selected").addClass("focus")):s.focus()}),e(document).on("click.nice_select",function(t){0===e(t.target).closest(".nice-select").length&&e(".nice-select").removeClass("open").find(".option")}),e(document).on("click.nice_select",".nice-select .option:not(.disabled)",function(t){var s=e(this),n=s.closest(".nice-select");n.find(".selected").removeClass("selected"),s.addClass("selected");var i=s.data("display")||s.text();n.find(".current").text(i),n.prev("select").val(s.data("value")).trigger("change")}),e(document).on("keydown.nice_select",".nice-select",function(t){var s=e(this),n=e(s.find(".focus")||s.find(".list .option.selected"));if(32==t.keyCode||13==t.keyCode)return s.hasClass("open")?n.trigger("click"):s.trigger("click"),!1;if(40==t.keyCode){if(s.hasClass("open")){var i=n.nextAll(".option:not(.disabled)").first();i.length>0&&(s.find(".focus").removeClass("focus"),i.addClass("focus"))}else s.trigger("click");return!1}if(38==t.keyCode){if(s.hasClass("open")){var l=n.prevAll(".option:not(.disabled)").first();l.length>0&&(s.find(".focus").removeClass("focus"),l.addClass("focus"))}else s.trigger("click");return!1}if(27==t.keyCode)s.hasClass("open")&&s.trigger("click");else if(9==t.keyCode&&s.hasClass("open"))return!1});var n=document.createElement("a").style;return n.cssText="pointer-events:auto","auto"!==n.pointerEvents&&e("html").addClass("no-csspointerevents"),this}}(jQuery);
Please let me know if there is a solution for this
My issue was sorted when I removed onchange="showChange()".

Add a class when specific dropdown is selected?

I want to reveal a link when a certain dropdown option is selected in a html5 form.
On page load I want to remove the link with id "pension-faq-icon" and only display it if the user selects <option value="<%= User::LENDER_TYPE_PENSION_INDIVIDUAL %>" id="select-ind-pension">Individual Pension Account</option>
Html:
<div class="seven columns">
<div class="select-holder icon icon_select">
<select name="user[user_subtype]" id="user_lender_type">
<option value="">Select type</option>
<option value="<%= User::LENDER_TYPE_INDIVIDUAL %>" id="select-ind">Individual Lender</option>
<option value="<%= User::LENDER_TYPE_PENSION_INDIVIDUAL %>" id="select-ind-pension">Individual Pension Account</option>
<!--<option value="sme" id="select-sme">Investment Business</option>-->
</select>
</div>
<p class="icon icon_info form-help-pension-faq show" id="pension-faq-icon">Need help? Read Our Pensions FAQ</p>
</div>
js file:
var user_type = $("#user_user_type").val();
var option_type = $("#select").val();
if(user_type == 'lender') {
$('#pension-faq-icon').addClass('display-none');
}
if (option_type == 'individual_pension_lender'){
//$('#pension-faq-icon').removeClass('display-none');
console.log(option_type);
}
Right now the code above is successfully not displaying the line with the id "pension-faq-icon". How can I add it again if the user selects the specific dropdown option mentioned above?
To make this work you need to attach a change event handler to the select which runs whenever the user selects an option. At the moment your logic only executes when the page loads.
Also note that you can simplify the process by providing a boolean to toggle() which specifies whether to hide or show the relevant element. Try this:
$('#user_lender_type').change(function() {
$('#pension-faq-icon').toggle($(this).val() == 'individual_pension_lender');
});
#pension-faq-icon {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="seven columns">
<div class="select-holder icon icon_select">
<select name="user[user_subtype]" id="user_lender_type">
<option value="">Select type</option>
<option value="lender" id="select-ind">Individual Lender</option>
<option value="individual_pension_lender" id="select-ind-pension">Individual Pension Account</option>
</select>
</div>
<p class="icon icon_info form-help-pension-faq show" id="pension-faq-icon">
Need help?
Read Our Pensions FAQ
</p>
</div>

Drop down price update

I am trying to build an app that let people choose a license and the price is different for different licenses. I want a real-time price update on the page of the product. Here is the reference that I took for the below code: https://stackoverflow.com/a/6740218
Code:
<script type="text/javaScript">
var price = {"3":"11","2":"500","1":"1000"};
$(function() {
$('select[name=dropdown_price_change]').change(function() {
document.getElementById('price_disp').innerHTML = price[$(this).val()];
});
// Trigger on dom ready
$('select[name=dropdown_price_change]').change();
});
</script>
<div class="product-price" id="price_disp">
<form class="cart nobottommargin clearfix" method="get">
<div class="quantity clearfix">
<select id="dropdown_price_change" name="dropdown_price_change" class="form-control">
<option value="3">Personal License</option>
<option value="2">Small Firm License</option>
<option value="1">Enterprise or Developer License</option>
</select>
</div>
</form>
</div>
Thanks in advance. ;)
innerHtml should be innerHTML and frankly, you should probably be using textContent instead of innerHTML in this case anyway since the values of the select don't contain any HTML.
Also, you shouldn't trigger the change function on document ready because the user will never get to see and use the dropdown list that way.
Lastly, add a "dummy" choice to the list as the default choice so that the user must change the value if they want to select "Personal License" from the list. Without this, the change event won't trigger because that was the default choice in the first place.
var price = {"3":"11","2":"500","1":"1000"};
$(function(){
$('select[name=dropdown_price_change]').change(function(){
document.getElementById('price_disp').textContent = price[$(this).val()];
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="product-price" id="price_disp">
<form class="cart nobottommargin clearfix" method="get">
<div class="quantity clearfix">
<select id="dropdown_price_change" name="dropdown_price_change" class="form-control">
<option value="">-- Select an Option --</option>
<option value="3">Personal License</option>
<option value="2">Small Firm License</option>
<option value="1">Enterprise or Developer License</option>
</select>
</div>
</form>
</div>

How to unhide select tag HTML?

I am trying to do the following in HTML and JavaScript:
I am using Select tag (HTML) that will be hidden until a user clicks on No.
If the user click on No, then the Select options appears and if the user select Yes, the Select options disappear. This function works great with input and other tags, but not select tag.
I did a lot of research and I found out that the display:none and select tag does not work with Google Chrome and IE, but all the solutions were given in JQuery and ASP.net. Since I am still new to all of this, I was wondering if there is a solution using HTML and JavaScript?
Code HTML:
<div id="divMetSpec" class="fieldRow">
<div class="leftLabel labelWidth20">
<label for="">Met Spec Upon Return:</label>
</div>
<div class="leftField">
<div class="formField68">
<input id="rbMetSpec" name="rbMetSpec" type="radio"
class="radiobuttonfield" alt="Met Spec" title="Met Spec" value="Yes"
onclick="javascript:KitFailure();" />Yes
<input id="rbMetSpec1" name="rbMetSpec" type="radio"
class="radiobuttonfield" alt="Met Spec" title="Met Spec" value="No"
onclick="javascript:KitFailure();" />No
</div>
</div>
</div>
<div id="KitFailure" style="display:none">
<p class="indent">To select multiple options - Please hold down the Ctrl
button to select:</p>
<div class="leftLabel labelWidth20">
<label for="txtKitFailure">Specify Failure:</label>
</div>
<div class="leftField">
<div class="formField40">
<select id="txtKitFailure" type="text" class="fieldRow"
name="KitFailure" multiple size="5">
<option value="Failure1">Failure 1</option>
<option value="Failure2">Failure 2</option>
<option value="Failure3">Failure 3</option>
<option value="Failure4">Failure 4</option>
<option value="Failure5">Failure 5</option>
<option value="Failure6">Failure 6</option>
<option value="Failure7">Failure 7</option>
<option value="Failure8">Failure 8</option>
</select>
</div>
</div>
</div>
Code JavaScript:
function KitFailure() {
if (document.getElementById('rbMetSpec1').checked) {
document.getElementById('KitFailure').style.display = 'none';
} else document.getElementById('KitFailure').style.display = 'block';
}
Thank you in advance for your help.
Irene
It works as is in IE11 + emulations, FF, Chrome, and Safari for Windows.
Some corrections:
type="text" is not valid attribute of select
Also use multiple="multiple"
Alt is not valid attribute of input

How to show specific content based on 3 drop down selections?

I would like to display a div depending on a user's selection from two drop down lists.
While I'm going to display 3 dropdown options to the users, I'm only going to generate the output based on the selection of the first two:
This means that I will have a total of 9 possible outputs based on the user's selection:
Beaches --> Chill
Beaches --> Fast-Paced
Beaches --> Both
Museums --> Chill
Museums --> Fast-Paced
Museums --> Both
Mountains --> Chill
Mountains --> Fast-Paced
Mountains --> Both
Just for similar reference, a few months ago, I used the following script to generate a specific output based on 2 drop down selections:
http://jsfiddle.net/barmar/ys3GS/2/
<body>
<h2>Find your Animal Name</h2>
<p>Select your birth month and your favorite color and find your animal name.</p>
<form>
<select id="month">
<option value="">- birth month -</option>
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
<label class="January" for="January">January Name</label>
<label class="February" for="February">February Name</label>
<label class="March" for="March">March Name</label>
<label class="April" for="April">April Name</label>
<label class="May" for="May">May Name</label>
<label class="June" for="June">June Name</label>
<label class="July" for="July">July Name</label>
<label class="August" for="August">August Name</label>
<label class="September" for="September">September Name</label>
<label class="October" for="October">October Name</label>
<label class="November" for="November">November Name</label>
<label class="December" for="December">December Name</label>
<select id="color">
<option value="">- favorite color -</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Red">Red</option>
</select>
<label class="Green" for="Green">Green Name</label>
<label class="Blue" for="Blue">Blue Name</label>
<label class="Red" for="Red">Red Name</label>
</form>
<p id="output"></p>
</body>
But this need is a little different. Any thoughts on how I can achieve this? In other words – once the user selected the two options, I want the corresponding div (out of the 9 options) to show up below.
Thanks so much!
You can create 9 div elements and each div element will have two data attributes. One for travel preference and one for style. Like so:
<div class="result" data-preference="beaches" data-style="chill"></div>
<div class="result" data-preference="beaches" data-style="fast-paced"></div>
<div class="result" data-preference="beaches" data-style="both"></div>
<div class="result" data-preference="museums" data-style="chill"></div>
<div class="result" data-preference="museums" data-style="fast-paced"></div>
<div class="result" data-preference="museums" data-style="both"></div>
<div class="result" data-preference="mountains" data-style="chill"></div>
<div class="result" data-preference="mountains" data-style="fast-paced"></div>
<div class="result" data-preference="mountains" data-style="both"></div>
<style>
.result {display:none;}
.result.active {display:block;}
</style>
Also, let's go ahead and add some CSS to hide these div elements, and then setup an active class so that we can display the div once the user has made their selections.
The select elements where the user makes a choice will have options, and each value will have to be identical to the data-preference and data-style values. When a user has made a selection in both of the dropdowns we'll grab all the div's and filter out the one that has the matching data attributes.
$('#preference, #style').on('change', function(){
// set reference to select elements
var preference = $('#preference');
var style = $('#style');
// check if user has made a selection on both dropdowns
if ( preference.prop('selectedIndex') > 0 && style.prop('selectedIndex') > 0 ) {
// remove active class from current active div element
$('.result.active').removeClass('active');
// get all result divs, and filter for matching data attributes
$('.result').filter('[data-preference="' + preference.val() + '"][data-style="' + style.val() + '"]').addClass('active');
}
});
jsfiddle: http://jsfiddle.net/EFM9b/1/
The following is jQuery will work for any number of select fields. It uses the values of the options as CSS classes which are then used to match against the results boxes.
No hiding or showing of the results happens until all select boxes are chosen.
JSFiddle
http://jsfiddle.net/chnZP/
CSS
#results-container > div { display: none; }
HTML
<div id='select-container'>
<select>http://jsfiddle.net/9Qpjg/15/#update
<option value='none'>Select Option</option>
<option value='alpha'>Alpha</option>
</select>
<select>
<option value='none'>Select Option</option>
<option value='red'>Red</option>
<option value='blue'>Blue</option>
</select>
<select>
<option value='none'>Select Option</option>
<option value='dog'>Dog</option>
<option value='cat'>Cat</option>
</select>
</div>
<div id='results-container'>
<div class='dog red alpha'> Alpha Red Dog</div>
<div class='dog blue alpha'> Alpha Blue Dog</div>
<div class='cat red alpha'> Alpha Red Cat</div>
<div class='cat blue alpha'> Alpha Blue Cat</div>
<div>
JavaScript
jQuery(function($){
var
selects = $('#select-container select'),
results = $('#results-container > div');
selects.change(function(){
var values = '';
selects.each(function(){
values += '.' + $(this).val();
});
results.filter(values).show().siblings().hide();
});
});
Careful naming of your divs will get you most of the way there, e.g.
<div class='itinerary' id="beaches_chill">...</div>
<div class='itinerary' id="beaches_fast-paced">...</div>
...
<div class='itinerary' id="mountains_both">...</div>
Now show or hide these based on your dropdowns:
$('#preference, #style').change(function() {
$('.itinerary').hide();
$('#' + $('#preference option:selected').val() + '_' + $('#style option:selected').val()).show();
});
(Another answer here suggests using attributes--that's nicer than using the id, so do that.)

Categories

Resources