Show divs based on dropdown-menu-option selected by user - javascript

The purpose with the code is to let user choose a number from a dropdown-menu and show corresponding divs. The startpoint of divs is always that all are hidden. The "user-selected-number" should be used by Javascript to decide how many divs to show. In this case as following:
Dropdown-value: 1 = show balance 0
Dropdown-value: 2 = show balance 0,1
Dropdown-value: 3 = show balance 0,1,2
Dropdown-value: 4 = show balance 0,1,2,3
Observation:
I suspect the problem is that the javavascript picks up only the option that is predefined as "selected" which would mean it does never take the user-selected-value for further processing.
The var_dump of $_POST shows correct result/printout, everytime user selects an option from the dropdown menu.
Wanted behavour:
The user should on the frontend be able to pick a value in dropdown between 1-4 and the corrensponding divs (see list above) should be made visible.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Show divs based on dropdown</title>
<style>
.balance_0,
.balance_1,
.balance_2,
.balance_3
{
display: none;
}
</style>
</head>
<body>
<!-- Form (Years-selector) -->
<form class="year-selector" method="post">
<select class="dropdown_result" id="dropdown_result" name="selection">
<option value="" selected="selected" hidden="hidden">Select amount of years to report...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<button type="submit" name="button">Send</button>
</form>
<!-- Divs -->
<div class="balance_0">Balance-0</div>
<div class="balance_1">Balance-1</div>
<div class="balance_2">Balance-2</div>
<div class="balance_3">Balance-3</div>
<pre>
<?php var_dump($_POST); ?>
<script>
// Extract selected dropdown menu option.
var amountOfBalanceColumnsToShow =
document.getElementById("dropdown_result").selectedOptions[0].value;
// Show amount of balance divs based on above form.
if (amountOfBalanceColumnsToShow == 1) {
var x = document.getElementById("balance_0");
x.style.display = "block";
}
else if (amountOfBalanceColumnsToShow == 2) {
for (var i = 0; i <= 1; i++) {
var x = document.getElementById("balance_" + i);
x.style.display = "block";
}
}
else if (amountOfBalanceColumnsToShow == 3) {
for (var i = 0; i <= 2; i++) {
var x = document.getElementById("balance_" + i);
x.style.display = "block";
}
}
else if (amountOfBalanceColumnsToShow == 4) {
for (var i = 0; i <= 3; i++) {
var x = document.getElementById("balance_" + i);
x.style.display = "block";
}
}
</script>
</body>
</html>

Added event.preventDefault so the form does not actually submit and refresh the page removing the client side event. Added a click event to the button and ran conditionals that sets the style attributes to block for the numbers selected.
I assume you want to show each numbers corresponding amount of their divs, so if 3 is selected show balance_0, balance_1, balance_2 correct?
let e = document.querySelector('#dropdown_result');
let send = document.querySelector('#button');
let one = document.querySelector('.balance_0');
let two = document.querySelector('.balance_1');
let three = document.querySelector('.balance_2');
let four = document.querySelector('.balance_3');
let selected;
send.addEventListener('click', event => {
selected = Number(e.options[e.selectedIndex].value);
if(selected === 1){
one.style.display = "block";
two.style.display = "none";
three.style.display = "none";
four.style.display = "none";
}else if(selected === 2){
one.style.display = "block";
two.style.display = "block";
three.style.display = "none";
four.style.display = "none";
}else if(selected === 3){
one.style.display = "bloc";
two.style.display = "block";
three.style.display = "block";
four.style.display = "none";
}else if(selected === 4){
one.style.display = "block";
two.style.display = "block";
three.style.display = "block";
four.style.display = "block";
}
event.preventDefault();
});
.balance_0,
.balance_1,
.balance_2,
.balance_3
{
display: none;
}
<form class="year-selector" method="post">
<select class="dropdown_result" id="dropdown_result" name="selection">
<option value="" selected="selected">Select amount of years to report...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<button type="submit" id="button" name="button">Send</button>
</form>
<!-- Divs -->
<div class="balance_0">Balance-0</div>
<div class="balance_1">Balance-1</div>
<div class="balance_2">Balance-2</div>
<div class="balance_3">Balance-3</div>

There are several things you should consider in your code.
You are using button with type="submit" which causes to pages get reload each time and run the same script, so the value of amountOfBalanceColumnsToShow will always be the same (which is in your case it is your first option in the dropdown).
You are always just showing the blocks in each particular condition and don't get any consideration of hiding unnecessary ones.
You are getting element by its id where the balance div's have classes instead of id's.
To fix these things, you should first add an event listener to your submit button and prevent its default action, then get all the elements with balance class and after that with your conditions iterate through them and specify which one has to be shown and which one has to hidden.
So your final code should be something like this:
// Extract selected dropdown menu option.
var element = document.getElementById("dropdown_result");
var submitButton = document.querySelector('button[type="submit"]');
var balanceDivs = document.querySelectorAll("[class*='balance']");
var balanceDivsLength = balanceDivs.length;
submitButton.addEventListener("click", function(event) {
event.preventDefault();
var amountOfBalanceColumnsToShow =
element.options[element.selectedIndex].value;
// Show amount of balance divs based on above form.
if (amountOfBalanceColumnsToShow == 1) {
for (var i = 0; i < balanceDivsLength; i++) {
if (balanceDivs[i].classList.contains("balance_0")) {
balanceDivs[i].style.display = "block";
} else {
balanceDivs[i].style.display = "none";
}
}
} else if (amountOfBalanceColumnsToShow == 2) {
for (var i = 0; i < balanceDivsLength; i++) {
if (
balanceDivs[i].classList.contains("balance_0") ||
balanceDivs[i].classList.contains("balance_1")
) {
balanceDivs[i].style.display = "block";
} else {
balanceDivs[i].style.display = "none";
}
}
} else if (amountOfBalanceColumnsToShow == 3) {
for (var i = 0; i < balanceDivsLength; i++) {
if (!balanceDivs[i].classList.contains("balance_3")) {
balanceDivs[i].style.display = "block";
} else {
balanceDivs[i].style.display = "none";
}
}
} else if (amountOfBalanceColumnsToShow == 4) {
for (var i = 0; i < balanceDivsLength; i++) {
balanceDivs[i].style.display = "block";
}
}
});
.balance_0,
.balance_1,
.balance_2,
.balance_3 {
display: none;
}
<!-- Form (Years-selector) -->
<form class="year-selector" method="post">
<select class="dropdown_result" id="dropdown_result" name="selection">
<option value="" selected="selected" hidden="hidden">Select amount of years to report...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<button type="submit" name="button">Send</button>
</form>
<!-- Divs -->
<div class="balance_0">Balance-0</div>
<div class="balance_1">Balance-1</div>
<div class="balance_2">Balance-2</div>
<div class="balance_3">Balance-3</div>

Related

Why my if condition isn't working with select box in javascript?

In my code, I am trying to make a code in which I want to get value of select box and add value accordingly but my code is getting a bunch of errors. Can anyone please help me. In code i just want to add 1 to selectbox value. E.g: If i pressed on S and add then 1 should be added to S Code:
function myFunction() {
var x = document.getElementById("issue").value;
var is1 = 0;
var is2 = 0;
var is3 = 0;
if (x == document.getElementById("issue").value) {
is1 = 1;
} else if (x == document.getElementById("issue").value) {
is2 = 1;
} else if (x == document.getElementById("issue").value) {
is3 = 1;
}
}
Enter issue code:
<select name="issue" id="issue">
<option value="i1">S</option>
<option value="i2">W</option>
<option value="i3">T</option>
</select>
<button onclick="myFunction()">Add</button>
You can simply create three variables and update their count based on the selected option.
let is1 = 0, is2 = 0, is3 = 0
function myFunction() {
var x = document.getElementById("issue").value;
if (x === "i1") is1++
else if (x === "i2") is2++
else if (x === "i3") is3++
document.getElementById("results").innerText=`Option S: ${is1}\nOption W: ${is2}\nOption T: ${is3}`
}
Enter issue code:
<select name="issue" id="issue">
<option value="i1">S</option>
<option value="i2">W</option>
<option value="i3">T</option>
</select>
<button onclick="myFunction()">Add</button>
<p id="results"></p>

How to create a select that depends on the value of another select?

I need to create a menu of regions hat display two lists: a <select> for the region and another <select> for the available municipalities of that region. For this, I have a <form> and I update the municipalities through JavaScript. I have problems assigning the municipalities as <option>s of the second <select>. The option matrix of the menu doesn't accept the assignment of the values.
Here's the code.
HTML.
<html>
<head>
<title>
Página menú principal.
</title>
<?!= incluirArchivo('ArchivoJS'); ?>
</head>
<body onLoad = "preparar();">
<form id="formularioConductor" name="formularioConductor" method="post" enctype="multipart/form-data" autocomplete = "on">
<select name="menuDepartamento" id="menuDepartamento" tabindex="2" accesskey="e" onChange="municipiosDepartamento();">
<option value="x" selected="selected">ELIJA UN DEPARTAMENTO</option>
<option value="0">Antioquia</option>
<option value="1">Atlántico</option>
</select>
<select name="menuMunicipios" id="menuMunicipios" tabindex="3" disabled>
<option value=0>TODOS LOS MUNICIPIOS</option>
</select>
</form>
</body>
</html>
Javascript code:
<script lenguage="javascript">
function preparar() {
document.forms[0].elements.numeroLicencia.focus();
document.forms[0].elements.nombreConductor.disabled = true;
document.forms[0].elements.botonEnviar.disabled = true;
document.forms[0].elements.botonActualizar.disabled = true;
}
function municipiosDepartamento() {
var arregloMunicipiosDepartamento = new Array();
var posicionMunicipio = document.forms[0].elements.menuDepartamento.value;
arregloMunicipiosDepartamento = municipiosColombia(posicionMunicipio);
if(document.forms[0].elements.menuMunicipios.options.length > 1){
var totalMunicipios = document.forms[0].elements.menuMunicipios.length;
for (var i = 1; i < totalMunicipios; i ++){
document.forms[0].elements.menuMunicipios.options[1] = null;
}
}
if(document.forms[0].elements.menuDepartamento.value === "x"){
document.forms[0].elements.menuMunicipios.selectedItem = 0;
document.forms[0].elements.menuMunicipios.disabled = true;
}
else
{
document.forms[0].elements.menuMunicipios.options.length = arregloMunicipiosDepartamento.length;
for (var i = 0; i < arregloMunicipiosDepartamento.length; i ++) {
var opcionTemporal = new Option(arregloMunicipiosDepartamento[i], (i+1));
***document.forms[0].elements.menuMunicipios.options[i+1].text = opcionTemporal.text;
document.forms[0].elements.menuMunicipios.options[i+1].value = opcionTemporal.value;***
}
document.forms[0].elements.menuMunicipios.disabled = false;
}
}
function municipiosColombia(posicion) {
var antioquia, atlantico, arregloTodos, arregloMunicipiosDepartamento = new Array();
antioquia=["Medellín","Abejorral","Abriaqui","Alejandria"];
atlantico = ["Barranquilla","Baranoa","Campo De La Cruz","Candelaria"];
arregloTodos = [antioquia, atlantico];
arregloMunicipiosDepartamento=arregloTodos[posicion];
return arregloMunicipiosDepartamento;
}
</script>
I have highlighted the work that doesn't work.
The way I would do what you describe is to clear out the options each time and recreate the required ones, then add them into the particular select, like so:
var regions = {};
regions['A'] = ['mu', 'ni', 'ci', 'pal', 'it', 'y'];
regions['B'] = ['I', 'like', 'bananas'];
var selRegion = document.getElementById('region');
selRegion.onchange = setMunicipalities;
var selMun = document.getElementById('municipality');
function setMunicipalities(e)
{
while(selMun.length > 0)
{
selMun.remove(0);
}
if(selRegion.selectedOptions[0].value === 'ALL')
{
for(var r in regions)
{
if(regions.hasOwnProperty(r))
{
addMunicipalities(regions[r]);
}
}
}
else
{
var reg = selRegion.selectedOptions[0].value;
addMunicipalities(regions[reg]);
}
}
function addMunicipalities(region)
{
var allMun = document.createElement('option');
allMun.setAttribute('value', 'ALL');
var allMunText = document.createTextNode('ALL');
allMun.appendChild(allMunText);
selMun.add(allMun);
for (var mi = 0; mi < region.length; mi++)
{
var m = region[mi];
var mun = document.createElement('option');
mun.setAttribute('value', m);
var munText = document.createTextNode(m);
mun.appendChild(munText);
selMun.add(mun);
}
}
setMunicipalities(null);
<label for="region">Region</label>
<select id="region">
<option selected="selected" value="ALL">ALL</option>
<option value="A">A</option>
<option value="B">B</option>
</select>
<label for="municipality">Municipality</label>
<select id="municipality">
</select>
I haven't read your entire code because I had a hard time reading code with contents not in English but anyway, I get what you're trying to do here. Suppose that your first select list contains "Region A" and "Region B" as options; "Municipality A1", "Municipality A2", "Municipality B1","Municipality B2" are the possible options for the second select list. Here's a function that will change the options of the second select list depending on what is selected on the first select list:
function optionChanger(v_selected){
var whatisselected= v_selected.options[v_selected.selectedIndex].value;
var municipalities= {};
municipalities['A'] = ['Municipality A1','Municipality A2'];
municipalities['B'] = ['Municipality B1','Municipality B2'];
v_selected.options.length=0; //remove the contents of the second select list
v_selected.options[0] = new Option(municipalities[whatisselected][0],municipalities[whatisselected][0],false,true);// set the first option of the second list as the default selected value
for(x=1;x<municipalities[whatisselected].length;x++){ //add the remaining options to the second list
v_selected.options[x] = new Option(municipalities[whatisselected][x],municipalities[whatisselected][x],false,false);
}
}
Then add this inside the tag of your FIRST select list:
onchange='optionChanger(this)'
PS: Please notice that the return value of the first select list must be 'A', 'B'

Check boxes validation in JavaScript

I have written this script:
function getDays(select){
var selectedString = select.options[select.selectedIndex].value;
if(selectedString == 4)
{
document.getElementById("days_target").style.display = "block";
}else {
document.getElementById("days_target").style.display = "none";
}
}
and in validateForm() function I have this:
var x=document.forms["form1"]["days"].value;
if (x==null || x=="" || x=="Select Days")
{
alert("Oh, you forgot to select days! :)");
return false;
}
var x=document.forms["form1"]["days"].value;
if(x=="4")
{
var cnt = 0;
for (var i = 7; i < document.day.elements.length; i++) {
if (document.day.elements[i].type == 'checkbox') {
if (document.day.elements[i].checked == true) {
cnt++;
}
}
}
if (cnt == 0) {
alert("Atleast 1 day Should be Selected.");
return false;
}
}
HTML like this:
<b>Please enter days required</b><br/>
<select name="days" id="days" style="width:200px;" onchange="getDays(this)">
<option value="Select Days" selected>Select Days</option>
<option value="1">Mon-Fri</option>
<option value="2">Mon-Fri</option>
<option value="3">Mon-Fri</option>
<option value="4">Bespoke Days</option>
</select><br/><br/>
<div id="days_target" style="display:none;">
<b>Select Days</b><br/>
<input type="checkbox" name="day" value="mon"/>Mon <input type="checkbox" name="day" value="tue"/>Tue<br/>
<input type="checkbox" name="day" value="wed"/>Wed <input type="checkbox" name="day" value="thr"/>Thr<br/>
<input type="checkbox" name="day" value="fri"/>Fri <input type="checkbox" name="day" value="sat"/>Sat<br/>
<input type="checkbox" name="day" value="sun"/>Sun<br/><br/>
</div>
If I select Bespoke days then that check boxes appear and if none is checked then I want to display error message "Atleast one day should be selected." How to do this?
You are accessing the checkboxes incorrectly. Forms have elements. Also you start from 7 and count up instead of from 0 and count up or from 6 and count down
var day = document.forms["form1"].day;
for (var i = 0; i < day.length; i++) {
if (day[i].type == 'checkbox') {
if (day[i].checked == true) {
cnt++;
}
}
}
I would do it like this:
Live Demo
var x=document.forms["form1"]["days"].selectedIndex;
if (x<1) {
alert("Please select days");
return false;
}
else if(x==4) { // fifth entry
var checked = false, chk = document.forms["form1"]["day"];
for (var i = 0; i < chk.length; i++) {
if (chk[i].checked) { checked=true; break }
}
if (!checked) {
alert("At least one day should be checked.");
return false;
}
}
The after function in jquery would allow you to easily do this. This would require two steps.
Load Jquery by putting this inside your header tag in the HTML (<head></head>):
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Add javascript in the validation when the condition is not met:
$('#days').after('<label class="error">Atleast one day should be selected.</label.');
Additionally, you will want the error message to go away when the validation rules are met.
$('.error').remove();
You will probably want to adjust the HTML/CSS for displaying purposes, but that should be enough to get you going.

select multiselect option limit up to 2

I am using multiselect for different subject's I want to limit the select up to 2 and make the other's disabled in the same way if user deselect, Again the option must be available for the user.
<select multiple="multiple" class="subjects" name="subjects[]" style="float:left;width:205px;" size="5">
<option value='1'>subject1</option>
<option value='2'>subject2</option>
<option value='3'>subject3</option>
<option value='3'>subject3</option>
</select>
So far I have achieved to deselect only the last option which was selected after 2 and the code is as follow
/**
* Make sure the subject's limit is 2
*/
$(".subjects option").click(function(e){
if ($(this).parent().val().length > 2) {
$(this).removeAttr("selected");
}
});
Thank you.
Improved jQuery example, notice the (else enable) option, this fixes a bug on previous examples that disabled the select options permanently. Also removed the "Please select only two options." error message when possible.
http://jsfiddle.net/c9CkG/25/
jQuery(document).ready(function () {
jQuery("select").on("change", function(){
var msg = $("#msg");
var count = 0;
for (var i = 0; i < this.options.length; i++)
{
var option = this.options[i];
option.selected ? count++ : null;
if (count > 2)
{
option.selected = false;
option.disabled = true;
msg.html("Please select only two options.");
}else{
option.disabled = false;
msg.html("");
}
}
});
});
As an improvment on RobG's answer, you could unselect an option if it makes count > 2.
See: http://jsfiddle.net/c9CkG/3/ for a working example using jQuery.
function checkSelected(el) {
var msgEl = document.getElementById('msg');
var count = 0;
for (var i=0, iLen=el.options.length; i<iLen; i++)
el.options[i].selected? count++ : null;
// Deselect the option.
if (count > 2) {
el.options[i].selected = false;
el.options[i].disabled = true;
msgEl.innerHTML = 'Please select only two options';
}
}
Something like the following will do the job:
function checkSelected(el) {
var msgEl = document.getElementById('msg');
var count = 0;
for (var i=0, iLen=el.options.length; i<iLen; i++)
el.options[i].selected? count++ : null;
msgEl.innerHTML = count > 2? 'Please select only two options' : '';
}
</script>
<span>Please select a maximum of two options:</span>
<select multiple onchange="checkSelected(this);">
<option>0
<option>1
<option>2
<option>3
</select>
<br>
<span id="msg"></span>
I don't think it's a good idea to disable options, you only care that only two are selected when the form is submitted. Until then, it doesn't matter.
$(document).ready(function() {
var last_valid_selection = null;
$('#testbox').change(function(event) {
if ($(this).val().length > 5) {
alert('You can only choose 5!');
$(this).val(last_valid_selection);
} else {
last_valid_selection = $(this).val();
}
});
});

Need help in adding selected items from selectbox to div (dynamic addition)

I need to display the selected sub-categories (multi) in the below div and also in some situations I need to close the div elements that are selected wrongly from the select box, so that I can add and delete elements to the div (by the above selectbox).
Even I made the similar code, but its not working for multi selection.
Briefly, I need the selected categories (multi) with close buttons in the below div.
<script type="text/javascript">
function selectlist() {
checkboxhome = document.getElementById("check");
catogery = document.getElementById("cat");
value = catogery.options[catogery.selectedIndex].value;
checkboxhome.innerHTML = "<br/> <p>" + value + "</p>";
}
</script>
<body>
<form action="#" enctype="multipart/form-data">
<select name="cat" id="cat" onchange="selectlist();" multiple="multiple">
<option>Select subcatogery</option>
<option value="fashion">Fashion</option>
<option value="jewelry">Jewelry</option>
<option value="dresses">dresses</option>
<option value="shirts">Shirts</option>
<option value="diamonds">Diamonds</option>
</select>
<div id="check">
</div></form>
</body>
</html>
Loop over the options and check if they are selected, something like this:
function selectlist() {
var checkboxhome = document.getElementById("check");
var category = document.getElementById("cat");
checkboxhome.innerHTML = '';
for (var i = 0; i < category.options.length; i++) {
if (category[i].selected) {
checkboxhome.innerHTML += "<p>" + category.options[i].value + "</p>";
}
}
}
Here is a fiddle of what could work for you: http://jsfiddle.net/maniator/W6gnX/
Javascript:
function selectlist() {
checkboxhome = document.getElementById("check");
catogery = document.getElementById("cat");
value = getMultiple(catogery);
checkboxhome.innerHTML = "<br/> <p>" + value + "</p>";
}
function getMultiple(ob)
{
var arSelected = new Array(), length = ob.length, i = 0, indexes = [];
while (ob.selectedIndex != -1 && i < length)
{
if (ob.selectedIndex != 0 && !in_array(ob.selectedIndex, indexes)) {
indexes.push(ob.selectedIndex)
arSelected.push(ob.options[ob.selectedIndex].value);
}
ob.options[ob.selectedIndex].selected = false;
i++;
}
var count = 0;
while(count < indexes.length){
ob.options[indexes[count]].selected = true;
count ++;
}
return arSelected;
}
function in_array(needle, haystack)
{
for(var key in haystack)
{
if(needle === haystack[key])
{
return true;
}
}
return false;
}

Categories