Making a div appear based on selection - javascript

First of all I have never really played with Javascript before, asides finding stuff that you clever types have created and then adding it to my sites.
I would like to show a div based on which option is selected in a drop down on the page.
I have Tariffs 1 - 4, the Tariff selected shows as t1, t2, t3 and t4 but the Divs are then not becoming visible.
I have tested the show / hide function of the div bit with a simple button and that worked, I just can't seem to make it pick up the variable to show the one which is selected.
<div>
Value Selected: <span id="current"></span>
<br>
<br>
<select id="select" name="options">
<option>Choose Your Option</option>
<option value="t1"> 1</option>
<option value="t2"> 2</option>
<option value="t3"> 3</option>
<option value="t4"> 4</option>
</select>
<div class="t1"><p>Tariff 1</p></div>
<div class="t2"><p>Tariff 2</p></div>
<div class="t3"><p>Tariff 3</p></div>
<div class="t4"><p>Tariff 4</p></div>
</div>
function showSelectedItem() {
var item = document.getElementById("select").value;
document.getElementById("current").innerHTML = item;
if (item.style.display === 'none') {
item.style.display = 'block';
} else {
item.style.display = 'none';
}
}
document.getElementById("select").addEventListener("change", showSelectedItem);
then the css for all the t1, t2... divs is
.t1
{display: none}
Thanks in advance, I suspect its something very obvious when you know what you are looking at.

Youe css styles wont be avaliable with item.style.display. Only the inline styles will be available with the above selector.
Logic
Make all nodes hidden initially with style="display:none" in HTML
On change, check the selected value.
Hide all nodes with class name which is not same as selected value.
If you want to hide the dropdown when the user selects an option, you could select the dropdown with document.getElementById("select") and set style.display = 'none'
function showSelectedItem() {
var item = document.getElementById("select").value;
document.getElementById("current").innerHTML = item;
const classes = ['t1', 't2', 't3', 't4'];
// Toggle visibility;
classes.forEach((classNode) => {
document.querySelector(`.${classNode}`).style.display = classNode === item ? 'block': 'none';
});
// Hide the dropdown when the user selects an option
document.getElementById("select").style.display = "none";
}
document.getElementById("select").addEventListener("change", showSelectedItem);
<div>
Value Selected: <span id="current"></span>
<br>
<br>
<select id="select" name="options">
<option>Choose Your Option</option>
<option value="t1"> 1</option>
<option value="t2"> 2</option>
<option value="t3"> 3</option>
<option value="t4"> 4</option>
</select>
<div class="t1" style="display: none;">
<p>Tariff 1</p>
</div>
<div class="t2" style="display: none;">
<p>Tariff 2</p>
</div>
<div class="t3" style="display: none;">
<p>Tariff 3</p>
</div>
<div class="t4" style="display: none;">
<p>Tariff 4</p>
</div>
</div>
If you want the css styles also to be reflfced with your script, you have to make use of Window.getComputedStyle() Reference
function showSelectedItem() {
var item = document.getElementById("select").value;
document.getElementById("current").innerHTML = item;
const selectedNode = document.querySelector(`.${item}`);
if (selectedNode) {
const displayValue = window.getComputedStyle(selectedNode).display;
const classes = ['t1', 't2', 't3', 't4'];
classes.forEach((classNode) => {
document.querySelector(`.${classNode}`).style.display = classNode === item ? 'block': 'none';
});
// Hide the dropdown when the user selects an option
document.getElementById("select").style.display = "none";
}
}
document.getElementById("select").addEventListener("change", showSelectedItem);
.t1, .t2, .t3, .t4 {
display: none;
}
<div>
Value Selected: <span id="current"></span>
<br>
<br>
<select id="select" name="options">
<option>Choose Your Option</option>
<option value="t1"> 1</option>
<option value="t2"> 2</option>
<option value="t3"> 3</option>
<option value="t4"> 4</option>
</select>
<div class="t1">
<p>Tariff 1</p>
</div>
<div class="t2">
<p>Tariff 2</p>
</div>
<div class="t3">
<p>Tariff 3</p>
</div>
<div class="t4">
<p>Tariff 4</p>
</div>
</div>

This is my solution here
1.) Add t-content class to you t1 - t4. This is easily to hide them in javascript later on.
.t-content {
display: none
}
<div class="t1 t-content"><p>Tariff 1</p></div>
<div class="t2 t-content"><p>Tariff 2</p></div>
<div class="t3 t-content"><p>Tariff 3</p></div>
<div class="t4 t-content"><p>Tariff 4</p></div>
2.) Slight modify your javascript code
function showSelectedItem() {
var item = document.getElementById("select").value;
document.getElementById("current").innerHTML = item;
// Select our target
var selected_div = document.getElementsByClassName(item)[0];
// Make all t-content hide first
var t_content = document.getElementsByClassName('t-content');
for (var i = 0; i < t_content.length; i++) {
t_content[i].style.display = 'none';
}
// Display our target div
selected_div.style.display = 'block';
}

You need to compare display property of div instead of value of dropdown.
var item = document.getElementById("select").value;
var dv = document.querySelector("."+item);
document.getElementById("current").innerHTML = item;
if (dv.style.display === 'none') {
dv.style.display = 'block';
} else {
dv.style.display = 'none';
}
https://jsfiddle.net/palak6041/9wj07ebv/17/
This will not hide other divs though you need to hide it with additional code
below example will hide other div, only selected div will be visible
https://jsfiddle.net/palak6041/9wj07ebv/25/

Related

Trying to select a value from a drop-down

One Form on the page I am accessing. This form has a dropdown with 3 options. I need to select the third option. Accessing the webpage from a C# program with cefsharp library (embedded web browser).
I can change the displayed text using
document.forms[0].getElementsByClassName('css-0 Select__single-value')[0].innerText="Keep in-play";
but this has not been registered. Have also tried to trigger input and change events but it is still not recognising my selection.
Any suggestions?
Here is the original DOM for the form:
<div class="bet-widget-optional-params">
<div class="bet-params">
<div class="param-wrapper"><span class="param-label"><a class="link" href="https://help.smarkets.com/hc/en-gb/articles/115003946591" target="_blank">Time In Force</a></span>
<div class="param-select">
<div class="css-0 Select custom-select-box Select menu-on-click">
<div class="css-0 Select__control">
<div class="css-0 Select__value-container Select__value-container--has-value">
<div class="css-0 Select__single-value">Default</div><input id="react-select-bet-param-selector-input" readonly="" tabindex="0" class="css-14uuagi" value=""></div>
<div class="css-0 Select__indicators"><span class="css-0 Select__indicator-separator"></span><span aria-hidden="true" class="Select__arrow-zone"><span class="Select__arrow"></span></span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
In JavaScript you can set the selectedIndex property.
elem.selectedIndex = 2;
Setting -1 will remove any selection, and any positive integer will select that item in the list (0-indexed)... so if you want the 3rd item, just set it to 2.
HTMLSelectElement.selectedIndex docs
The property works as a getter too, so if you want to know which element is selected, you can request it like:
var currentSelectedIndex = elem.selectedIndex;
Full interactive example below:
var selectElem = document.getElementById('select');
var pElem = document.getElementById('p');
var buttonElem = document.getElementById('button');
selectElem.addEventListener('change', function() {
var index = selectElem.selectedIndex;
pElem.innerHTML = 'selectedIndex: ' + index;
});
buttonElem.addEventListener('click', function(){
selectElem.selectedIndex = 2;
});
<p id="p">selectedIndex: 0</p>
<select id="select">
<option selected>Option A</option>
<option>Option B</option>
<option>Option C</option>
<option>Option D</option>
<option>Option E</option>
</select>
<input type="button" id="button" value="Set it to C (2)"/>

Choosing option from dropdown menu does not show what it should

Maybe someone can tell me how i can repair problem with choosing from Paypal/Bitcoin/Credit Card, coz i tried almost everything, nothing work like it should
I tried also to make them child()/children()/next() and so on nothing help
<select id="payment" name="user-payment">
<option value="select method">Select Payment Method</option>
<option value="Credit Card">Credit Card</option>
<option value="PayPal">PayPal</option>
<option value="Bitcoin">Bitcoin</option>
</select>
$paymentOptionsCard.change(()=>{
// if credit card
if($paymentOptions.val()==='Credit Card'){
$creditCard.show();
bullPay = true;
}
else{
$creditCard.hide();
bullPay = false;
}
});
$paymentOptionsPaypal.change(()=>{
if($paymentOptionsPaypal.val()==="PayPal"){
$paypal.show();
bullPay = true;
}
else{
$paypal.hide();
bullPay = false;
}});
$paymentOptionsBitcoin.change(()=>{
//if bitcoin
if($paymentOptionsBitcoin.val()==="Bitcoin"){
$bitcoin.show();
bullPay = true;
}
else{
$bitcoin.hide();
bullPay = false;
}
});
That's the variables /
//getting payment options
const $paymentOptions = $("#payment");
//selecting default as Credit card
const $paymentOptionsBitcoin = $paymentOptions.val("Bitcoin");
const $paymentOptionsPaypal = $paymentOptions.val("PayPal");
const $paymentOptionsCard = $paymentOptions.val("Credit Card");
I expect that code will "show" or 'hide' values and if that true or false attribute will assign it to the variables.
Now it only show, without assigning all of them
You bind to the select with the change, not its options. You should just bind one change event to the select. This is a easy way of doing it without repeating a lot of code.
// reference the select element
var sel = document.querySelector('#payment')
// add change event
sel.addEventListener('change', () => {
// get the section that is active
var paymentActive = document.querySelector('.payment-section.active')
// if we have one hide it.
if (paymentActive) paymentActive.classList.remove("active")
// reference the option value that was selected
var selection = sel.value
// select the section based on the value
var payment = document.querySelector("#" + selection)
// show the section
if (payment) payment.classList.add("active")
})
.payment-section {
display: none;
}
.payment-section.active {
display: block;
}
<select id="payment" name="user-payment">
<option value="select method">Select Payment Method</option>
<option value="CreditCard">Credit Card</option>
<option value="PayPal">PayPal</option>
<option value="Bitcoin">Bitcoin</option>
</select>
<div id="CreditCard" class="payment-section">Credit Card</div>
<div id="PayPal" class="payment-section">Pay Pal</div>
<div id="Bitcoin" class="payment-section">Bitcoin</div>
I am not very clear of the question but one mistake I can point out is that on the second and third onchange event the "if" condition seems to be wrong
if($paymentOptionsPaypal.val()==="PayPal")
if($paymentOptionsBitcoin.val()==="Bitcoin")
should have been
if($paymentOptions.val()==="PayPal")
if($paymentOptions.val()==="Bitcoin")
$(function() {
$('#payment').change(function(){
$('.colors').hide();
var pm= $(this).val();
$('#' + pm).show();
if(pm=='credit_Card'){
console.log('Credit Card');
}
else if(pm=='payPal'){
console.log('PayPal');
}
else if(pm=='bitcoin'){
console.log('Bitcoin');
}
});
});
#credit_Card,#payPal,#bitcoin {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button dropdown">
<select id="payment">
<option value="">Select Payment Method</option>
<option value="credit_Card">Credit Card</option>
<option value="payPal">PayPal</option>
<option value="bitcoin">Bitcoin</option>
</select>
</div>
<div class="output">
<div id="credit_Card" class="colors red"> Your Payment method is Credit Card</div>
<div id="payPal" class="colors yellow"> Your Payment method is PayPal</div>
<div id="bitcoin" class="colors blue"> Your Payment method is Bitcoin</div>
</div>
<footer>
<small>

Dropdown selection loads image and another dropdown menu loads info on another column

I have to make a dropdown menu in which selection of an option loads an image under it, and it also shows another dropdown menu under the image with options related to the selection.
Now this second dropdown menu, when I select an option, I need an image and some info to load in another column on the same page. I'm new to JS so a bit too ignorant.
<div class="row">
<select>
<option value="1">Please select an author:</option>
<option value="2">Gillian Flynn</option>
<option value="3">Robert Galbraith</option>
<option value="4">Khaled Hosseini</option>
</select>
</div>
document.getElementsByTagName('select')[0].onchange = function() {
var elements = document.getElementsByClassName("toggleContent");
for(var i = 0, length = elements.length; i < length; i++) {
elements[i].style.display = 'none';
}
var value = this.options[this.selectedIndex].value;
document.getElementById(value).style.display = "block";
}
.toggleContent{
display:none;
}
.defaultContent{
display:block;
}
<div class="row">
<select>
<option value="1">Please select an author:</option>
<option value="2">Gillian Flynn</option>
<option value="3">Robert Galbraith</option>
<option value="4">Khaled Hosseini</option>
</select>
</div>
<div id="1" class="toggleContent defaultContent">11111111111111111111</div>
<div id="2" class="toggleContent">22222222222222222222</div>
<div id="3" class="toggleContent">33333333333333333333</div>
<div id="4" class="toggleContent">44444444444444444444</div>

javascript to display div element based on a calculated value

I am trying to display a different div elements based on a calculated value, basically
if(x <= total){display y <div>} else {display z <div>}
I cannot figure out what part of the div I need to capture to display the div, right now my conditional statement doesn't work, it only shows the div after the button is pushed. The var surlyValue is being set properly. Here is the HTML for the button
<button type="button" onclick="show('fixingSteps');">What Do I Need To Do?</button>
This is the HTML for the 2 options
<div class="side-by-side" id="fixingSteps" name="fixingSteps" style="background: aquamarine; display: none">
<h1>Recommended Mitigations</h1>
<div> Smile, Everyone Should Be Happy, No Mitigations are Neccessary!!!!</div>
</div>
<div class="side-by-side" id="fixingSteps" name="fixingSteps1" style="background: aquamarine; display: none">
<h1>Recommended Mitigations</h1>
<div>
<select id="mitS" name='mitS' onchange="calculateTotalWithMitigation()">
<option value="none">Select Input</option>
<option value="mit1">Mitigation 1</option>
<option value="mit2">Mitigation 2</option>
<option value="mit3">Mitigation 3</option>
<option value="mit4">Mitigation 4</option>
<option value="mit5">Mitigation 5</option>
</select>
</div>
And this the the JS function I am trying to use
function show(elementId) {
var surlyValue = getValue();
if (surlyValue < 10) {
document.getElementById("fixingSteps").style.display = "none";
document.getElementById(elementId).style.display = "block";
} else {
document.getElementsByName("fixingSteps1").style.display = "block";
}
}
Thanks for helping me learn how to use JS on this example

Div's visibility with javascript - problem

I am trying to use div's to display content on my page. This is controlled with an onchange element in a select menu. It works perfectly but the problem is I want one div to close when another one is opened. The div's open fine but it does not close the others. An example code is below. What am I doing wrong?
JavaScript:
if(document.getElementById('catgry').value == '01'){
document.getElementById('post04').style.visibility = "visible";
document.getElementById('post04').style.display = "";
document.getElementById('post07').style.visibility = "hidden";
document.getElementById('post07').style.display = "none";
}else if(document.getElementById('catgry').value == '02'){
document.getElementById('post02').style.visibility = "visible";
document.getElementById('post02').style.display = "";
document.getElementById('post04').style.visibility = "hidden";
document.getElementById('post04').style.display = "none";
document.getElementById('post07').style.visibility = "hidden";
document.getElementById('post07').style.display = "none";
}
HTML:
<div id="post04" style="visibility:hidden; display:none;">
<table class="posttb"><tr>
<td width="30%">Author</td>
<td><input type="text" name="author" size="30" class="postfd"></td>
</tr>
</table>
</div>
Hard to say without seeing your markup, but it could be as simple as this:
Example: http://jsfiddle.net/jtfke/
var posts = document.getElementById('posts').children;
document.getElementById('catgry').onchange = function() {
for( var i = 0, len = posts.length; i < len; i++ ) {
posts[ i ].style.display = (i == this.selectedIndex) ? 'block' : '';
}
};
example html
<select id='catgry'>
<option value='post01'>post 1</option>
<option value='post02'>post 2</option>
<option value='post03'>post 3</option>
<option value='post04'>post 4</option>
</select>
<div id='posts'>
<div>post 1 content</div>
<div>post 2 content</div>
<div>post 3 content</div>
<div>post 4 content</div>
</div>
Consider using jQuery and the jQuery accordion
http://jqueryui.com/demos/accordion/
You can do it with pure Javascript and some looping.
<form method="post" action="#">
<select id="selectMenu">
<option id="option1" value="option 1">option 1</option>
<option id="option2" value="option 2">option 2</option>
<option id="option3" value="option 3">option 3</option>
</select>
</form>
<div id="div1" class="postDiv">Div 1</div>
<div id="div2" class="postDiv">Div 2</div>
<div id="div3" class="postDiv">Div 3</div>
<script type="text/javascript">
init();
function init()
{
addListeners();
}
function addListeners()
{
document.getElementById("selectMenu").onchange = selectChange;
}
function selectChange(evt)
{
for(var i=0;i<evt.currentTarget.length;i++)
{
if(i == evt.currentTarget.selectedIndex)
{
adjustDivs(i+1, evt.currentTarget.options);
}
}
}
function adjustDivs(optionId, options)
{
document.getElementById("div" + optionId).style.display = "block";
for(var i=0;i<options.length;i++)
{
if(i != (optionId-1))
{
document.getElementById("div" + (i+1)).style.display = "none";
}
}
}
</script>
http://jsfiddle.net/hGxfS/
Install jquery;
Use this code as html markup for select box . remember to specify id=visibiitySelector and providean attribute "_showelement" for each option value, that matches with the id of the div you want to display if option is selected
<select id="visibilitySelector">
<option value="whatever" _showelement="post01">whatever</option>
<option value="whatever" _showelement="post02">whatever</option>
</select>
Copy this function into the javascripts of the page
$(document).ready(function(){
$('#visibilitySelector').change(function(){
var showelement = $('#visibilitySelector option:selected').attr('_showelement');
$('div.showhide').not('#' + showelement ).hide();
$('#' + showelement ).show();
});
});
Code the divs as below, remembering to provide class "showhide"
<div id="post01" class="showhide">
</div>
<div id="post01" class="showhide">
</div>
<div id="post01" class="showhide">
</div>

Categories

Resources