Change visibility of div when option is changed inside dropbox - javascript

I got codes like this inside my php:
<section id="placeOrder">
<h2>Place order</h2>
Your details
Customer Type:
<select name="customerType">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
and these are the divs of which visibility has to be changed according to the selected option:
<div id="retCustDetails" class="custDetails">
Forename <input type="text" name="forename" id="forename" />
Surname <input type="text" name="surname" id="surname" />
</div>
<div id="tradeCustDetails" class="custDetails" style="visibility:hidden">
Company Name <input type="text" name="companyName" id="companyName" />
</div>
I tried this javascript:
<script>
document.getElementsByName("customerType").onchange = function () {
var val = this.options[this.selectedIndex].value;
document.getElementById("tradeCustDetails").style.visibility = (val == "trd") ? "visible" : "hidden";
document.getElementById("retCustDetails").style.visibility = (val == "trd") ? "hidden" : "visible";
};
</script>
But div tradecustdetails" does not appear and div retCustDetails is still on there.
Can anyone help?

getElementsByName() returns a collection of all elements in the document with the specified name. Hence you have to loop through them like this:
var x = document.getElementsByName("customerType");
for (var i = 0; i < x.length; i++) {
// do something with x[i]
}
If you are using only one select element, then it is better to use getElementById() like this:
HTML
<select id="customerType" name="customerType">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
Script
document.getElementById("customerType").onchange = function () {
var val = this.options[this.selectedIndex].value;
document.getElementById("tradeCustDetails").style.visibility = (val == "trd") ? "visible" : "hidden";
document.getElementById("retCustDetails").style.visibility = (val == "trd") ? "hidden" : "visible";
};

Updated your script, this should work.
<script>
function jsFunction() {
var val = document.getElementById("dropSelect").options[document.getElementById("dropSelect").selectedIndex].value;
document.getElementById("tradeCustDetails").style.visibility = (val == "trd") ? "visible" : "hidden";
document.getElementById("retCustDetails").style.visibility = (val == "trd") ? "hidden" : "visible";
}
</script>
Update your dropdown HTML as well.
<select id="dropSelect" name="customerType" onchange="jsFunction()">
EDIT #1: using getElementsByName()
function jsFunction() {
var val = document.getElementsByName("customerType")[0];
val = val.options[val.selectedIndex].value;
document.getElementById("tradeCustDetails").style.visibility = (val == "trd") ? "visible" : "hidden";
document.getElementById("retCustDetails").style.visibility = (val == "trd") ? "hidden" : "visible";
}

Related

Show field based on selection (JS)

I'm trying to show fields based on what is selected in menu select option.
I tried some JS with the help of other posts found here on Stackoverflow, but failed.
I'm a fan, i dont know js well, i hope to find help with this question. Thanks to everyone for any answers, I leave the info below.
I would like to show the result of this:
var dayli_intake_mass = ((+ target) / 100 * (+ tdee) + (+ tdee));
only when mass1, mass2 or mass3 is selected.
Otherwise
I would like to show the result of this:
var dayli_intake_def = ((+ tdee) - (+ target) / 100 * (+ tdee));
only when def1, def2 or def3 is selected.
So, the mass1, mass2 and mass3 selection should show dayli_intake_mass
While the selection def1, def2 and def3 should show dayli_intake_def
Point 1 is an addition, point 2 is a subtraction. I don't want both to be visible, but only one of the two fields based on the selection.
I apologize for the bad English :(
<div class="fieldcontainer">
<input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" class="mts-field" maxlength="4" id="tdee" name"tdee" placeholder="Inserisci il tuo TDEE" form="fbday" required autocomplete="off"/>
<label>Spesa calorica</label>
</div>
<div class="container_level">
<select class="target" id="target_select" form="fbday" name="target">
<option value="0">Stile di vita / Attività fisica</option>
<option id="mass1" name="radsa" value="5">mass1</option>
<option id="mass2" name="radsa" value="10">mass2</option>
<option id="mass3" name="radsa" value="15">mass3</option>
<option id="def1" name="radsa" value="10">def1</option>
<option id="def2" name="radsa" value="15">def2</option>
<option id="def3" name="radsa" value="20">def3</option>
</select>
</div>
<!---Fabbisogno Giornaliero--->
<div id="fbbday0" class="results" hidden>
<input type="text" form="fbday" class="result-field" id="dayli_intake_mass" name="dayli_intake"
placeholder="Fabbisogno giornaliero / 0.000 Kcal" min="1" readonly/>
<label class="mts-label"></label>
</div>
<div id="fbbday1" class="results" hidden>
<input type="text" form="fbday" class="result-field" id="dayli_intake_def" name="dayli_intake"
placeholder="Fabbisogno giornaliero / 0.000 Kcal" min="1" readonly/>
<label class="mts-label"></label>
</div>
<form action="" id="fbday">
</form>
<button name="calculate" onclick="calculate()">Calculate</button>
<button id="reset" onclick="resetFields()">Reset</button>
calculate = function()
{
var tdee = document.getElementById('tdee').value;
var target = document.querySelector('#target_select option:checked').value;
var dayli_intake_mass = ((+target)/100*(+tdee)+(+tdee));
var kcal = "Devi assumere "+dayli_intake_mass.toLocaleString('it-IT',{maximumFractionDigits: 0}) + " Kcal"; document.getElementById('dayli_intake_mass').value = kcal;
var dayli_intake_def = ((+tdee)-(+target)/100*(+tdee));
var kcal = "Devi assumere "+dayli_intake_def.toLocaleString('it-IT',{maximumFractionDigits: 0}) + " Kcal"; document.getElementById('dayli_intake_def').value = kcal;
//This is Target Radio Selection//
var mass1 = document.getElementById('mass1').value;
var mass2 = document.getElementById('mass2').value;
var mass3 = document.getElementById('mass3').value;
var def1 = document.getElementById('def1').value;
var def2 = document.getElementById('def2').value;
var def3 = document.getElementById('def3').value;
//This is HideShow Result//
var conditional = document.querySelector('#target_select option:checked').value;
document.getElementById('dayli_intake_mass').hidden = conditional !== '5';
document.getElementById('dayli_intake_mass').hidden = conditional !== '10';
document.getElementById('dayli_intake_mass').hidden = conditional !== '15';
document.getElementById('dayli_intake_def').hidden = conditional !== '10';
document.getElementById('dayli_intake_def').hidden = conditional !== '15';
document.getElementById('dayli_intake_def').hidden = conditional !== '20';
}
https://jsfiddle.net/snake93/w1nLbhxv/81/
Edited
you can use change event to handle that
when you select one of the list it's will call change event then check or execute your code
because of there's some values like each other for example mass2 value = 10 and also def1 value = 10 .
because of that you can't only compare the values but also you need to compare the element id so i added the id's in the comparison operation
Here's the code
var target_select = document.getElementById("target_select");
target_select.addEventListener("change", function () {
var tdee = document.getElementById('tdee').value;
var target = document.querySelector('#target_select option:checked');
var fbbday1 = document.getElementById('fbbday1'),
fbbday0 = document.getElementById('fbbday0')
var dayli_intake_mass = ((+target.value)/100*(+tdee)+(+tdee));
var dayli_intake_def = ((+tdee)-(+target.value)/100*(+tdee));
//This is Target Radio Selection//
var mass1 = document.getElementById('mass1').value;
var mass2 = document.getElementById('mass2').value;
var mass3 = document.getElementById('mass3').value;
var def1 = document.getElementById('def1').value;
var def2 = document.getElementById('def2').value;
var def3 = document.getElementById('def3').value;
var massArr = [mass1, mass2, mass3],
deffArr = [def1, def2, def3]
if(massArr.indexOf(this.value) != -1 && target.id === 'mass1' || target.id === 'mass2' || target.id === 'mass3') {
fbbday0.removeAttribute('hidden')
document.getElementById('dayli_intake_mass').value = dayli_intake_mass;
} else {
fbbday0.setAttribute('hidden', true)
}
if(deffArr.indexOf(this.value) != -1 && target.id === 'def1' || target.id === 'def2' || target.id === 'def3') {
fbbday1.removeAttribute('hidden')
document.getElementById('dayli_intake_def').value = dayli_intake_def;
} else {
fbbday1.setAttribute('hidden', true)
}
});
First, I edited the values of the select options to be as below:
<select class="target" id="target_select" form="fbday" name="target" (onChange)="showHideIntake($event)">
<option value="0">Stile di vita / Attività fisica</option>
<option id="mass1" name="radsa" value="5">mass1</option>
<option id="mass2" name="radsa" value="10">mass2</option>
<option id="mass3" name="radsa" value="15">mass3</option>
<option id="def1" name="radsa" value="-10">def1</option>
<option id="def2" name="radsa" value="-15">def2</option>
<option id="def3" name="radsa" value="-20">def3</option>
</select>
Second, I added an event called (onChange) to the select element as shown in the first line in the previous point.
Third, I added an eventListener to the select element to handle the (onChange) event, as below:
const target_select = document.querySelector('#target_select');
const dayli_intake_mass = document.querySelector('#dayli_intake_mass');
const dayli_intake_def = document.querySelector('#dayli_intake_def');
target_select.addEventListener('change', (event) => {
console.log(+event.target.value); // just for checking selected option
// the + (plus sign) is to convert from string to number
dayli_intake_mass.hidden = dayli_intake_def.hidden = true;
event.target.value > 0 ? dayli_intake_mass.hidden = false :
dayli_intake_def.hidden = false;
});
With this, dayli_intake_mass and dayli_intake_def are shown or hidden upon the select option. Plus, you can use the value of the select option directly upon select one option of them.

show multiple text when select option is select

I have multiple div, I want to display 2 hidden text when I select the value of 1, when I choose value of 2 it will display 4 hidden text etc.
function showDiv(divId, element) {
document.getElementById('depositProductType').addEventListener('change', function() {
var style = this.value == 1 ? 'block' : 'none';
document.getElementById('allowJoint').style.display = style;
document.getElementById('allowTransfer').style.display = style;
var style = this.value == 2 ? 'block' : 'none';
document.getElementById('allowJoint').style.display = style;
document.getElementById('allowTransfer').style.display = style;
document.getElementById('allowDisabling').style.display = style;
document.getElementById('createOne').style.display = style;
var style = this.value == 3 ? 'block' : 'none';
document.getElementById('allowTransfer').style.display = style;
document.getElementById('createOne').style.display = style;
});
}
<select id="depositProductType" name="prod_type" onchange="showDiv('allowJoint','allowTransfer','allowDisabling','createOne', this)">
<option class="blank" value="">Please select</option>
<option value="1">Fixed Deposit</option>
<option value="2">Savings Deposit</option>
<option value="3">Scheduled Deposit</option>
</select>
<!-- this is the multiple div I want to display from my html -->
<div id="allowJoint"> ------- </div>
<div id="allowTransfer"> ------ </div>
<div id="allowDisabling"> ------- </div>
<div id="createOne"> ---------- </div>
First change you select to only pass the element
<select id="depositProductType" name="prod_type" onchange="showDiv(this)">
Then you showDiv can no need to listen to event since it is trigger by the onChange event already. Just call your function.
function showDiv(ele) {
var allowJoint = document.getElementById('allowJoint');
var allowTransfer = document.getElementById('allowTransfer');
var allowDisabling = document.getElementById('allowDisabling');
var createOne = document.getElementById('createOne');
if(ele.value == 1) {
allowJoint.style.display = 'block';
allowTransfer.style.display = 'block';
allowDisabling.style.display = 'none';
createOne.style.display = 'none';
}
else if(ele.value == 2) {
allowJoint.style.display = 'block';
allowTransfer.style.display = 'block';
allowDisabling.style.display = 'block';
createOne.style.display = 'block';
}
else if(ele.value == 3) {
allowTransfer.style.display = 'block';
createOne.style.display = 'block';
allowJoint.style.display = 'none';
allowDisabling.style.display = 'none';
}
}
function showDiv(element) {
var old_element = document.getElementById("depositProductType");
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);
document.getElementById('depositProductType').addEventListener('change', function() {
console.log(this.value)
document.getElementById('allowJoint').style.display = (this.value == 1 || this.value == 2) ? 'block' : 'none';
document.getElementById('allowTransfer').style.display = (this.value == 1 || this.value == 2) ? 'block' : 'none';
document.getElementById('allowDisabling').style.display = (this.value == 3 || this.value == 2) ? 'block' : 'none';
document.getElementById('createOne').style.display = (this.value == 3 || this.value == 2) ? 'block' : 'none';
});
}
<select id="depositProductType" name="prod_type" onchange="showDiv(this)">
<option class="blank" value="0">Please select</option>
<option value="1">Fixed Deposit</option>
<option value="2">Savings Deposit</option>
<option value="3">Scheduled Deposit</option>
</select>
<!-- this is the multiple div I want to display from my html -->
<div id="allowJoint" style="display: none"> allowJoint </div>
<div id="allowTransfer" style="display: none"> allowTransfer </div>
<div id="allowDisabling" style="display: none"> allowDisabling </div>
<div id="createOne" style="display: none"> createOne </div>

Filtering through multiple times in javascript

So, I have an object named products that has 3 attributes:
var products = [
{"name":"product1","size":"large","color":"blue","gender":"male"},
{"name":"product2","size":"small","color":"pink","gender":"female"},
{"name":"product3","size":"large","color":"green","gender":"male"},
{"name":"product4","size":"large","color":"yellow","gender":"female"},
{"name":"product5","size":"medium","color":"blue","gender":"female"},
{"name":"product6","size":"large","color":"green","gender":"male"},
{"name":"product7","size":"small","color":"yellow","gender":"male"},
{"name":"product8","size":"medium","color":"red","gender":"female"},
{"name":"product9","size":"large","color":"blue","gender":"male"},
{"name":"product10","size":"small","color":"red","gender":"female"}
];
So, if I have 3 select boxes for size, color, and gender, how would I filter these 3 to get the product name?
I'm trying to use .filter in javascript. I know how to use it in non-associative arrays. But, what about associative arrays? how do you use them?
var color = document.getElementById("color").value;
var gender = document.getElementById("gender").value;
var size = document.getElementById("size").value;
var matched = products.filter(function(e) {
return (e.color == color && e.gender == gender && e.size == size);
}).map(function(e) { return e.name; });
I wrote a JSfiddle to go with this answer. Check it out here: http://jsfiddle.net/THEtheChad/XjGPt/
JQuery
$('input').change(function(){
var names = filter();
});
function filter(){
var selected = {
size: $('#size') .val(),
color: $('#color') .val(),
gender: $('#gender').val()
};
var matches = products.filter(function(product){
return product.size == selected.size &&
product.color == selected.color &&
product.gender == selected.gender;
});
return matches.map(function(product){ return product.name });
}
Vanilla JS
var d = document;
var inputs = d.getElementsByTagName('input');
// Convert to array
inputs = Array.prototype.slice.call(inputs);
inputs.forEach(function(input){
input.addEventListener('change', function(e){
var names = filter();
});
});
function filter(){
var selected = {
size: d.getElementById('size') .value,
color: d.getElementById('color') .value,
gender: d.getElementById('gender').value
};
var matches = products.filter(function(product){
return product.size == selected.size &&
product.color == selected.color &&
product.gender == selected.gender;
});
return matches.map(function(product){ return product.name });
}
Not as elegant as Barmar's code, I implemented 2 out of the 3 dropboxes and left a bit of work for you as well ;)
<html>
<head>
<script>
var products = [
{"name":"product1","size":"large","color":"blue","gender":"male"},
{"name":"product2","size":"small","color":"pink","gender":"female"},
{"name":"product3","size":"large","color":"green","gender":"male"},
{"name":"product4","size":"large","color":"yellow","gender":"female"},
{"name":"product5","size":"medium","color":"blue","gender":"female"},
{"name":"product6","size":"large","color":"green","gender":"male"},
{"name":"product7","size":"small","color":"yellow","gender":"male"},
{"name":"product8","size":"medium","color":"red","gender":"female"},
{"name":"product9","size":"large","color":"blue","gender":"male"},
{"name":"product10","size":"small","color":"red","gender":"female"}
];
function checkValidOption(){
var color_chosen = document.getElementById("color").value;
var size_chosen = document.getElementById("size").value;
var result = "";
//only if both options were chosen
if (color_chosen !== "empty" && size_chosen != "empty"){
for(var i=0; i<products.length; i++){
if(products[i].size == size_chosen && products[i].color == color_chosen){
result = products[i].name;
break;
}
}
document.getElementById('result').innerHTML = result;
}
}
</script>
</head>
<body>
<div id="wrapper">
<select id="size" name="size" onchange="checkValidOption();">
<option value="empty"/>
<option value="small">small</option>
<option value="medium">medium</option>
<option value="large">large</option>
</select>
<select id="color" name="color" onchange="checkValidOption();">
<option value="empty"/>
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
<option value="green">green</option>
<option value="pink">pink</option>
</select>
</div><!--wrapper-->
<div id="result"></div>
</body>
</html>

Dynamically added options to selectbox do not delete

I can't seem to quite figure this out.
My functions work as they should however, there is one discrepancy, when the option values are added dynamically from the input box, and I hit the delete key in the [list1] , they do not get removed. However, if the option values are added statically, then they delete just fine as they should. Any ideas?
I am really scratching my head with this one.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function add_refdoc() {
var x = document.getElementById("list1");
var option = document.createElement("option");
var input = document.getElementById('refdocs_input')
option.text = input.value
x.add(option,x.option)
x.selectedIndex = x.options.length - 1;
}
function del_refdoc(e) {
var evt = e ? e : event;
var sel = evt.target ? evt.target : evt.srcElement;
if(evt.keyCode && evt.keyCode == 46 || evt.which == 46) {
var val = sel.value;
var opts = sel.getElementsByTagName("option");
if(val != "") {
for(var i=0; i<opts.length; i++) {
if(val == opts[i].value)
sel.removeChild(opts[i]);
}
}
}
}
</script>
</head>
<body>
<input id="refdocs_input" type="text"/>
<input value="add" type="button" onclick="add_refdoc()"/>
<br>
<select onkeydown="del_refdoc(event)" style="width: 250px;" id="list1"></select>
<br><br>
<select onkeydown="del_refdoc(event)" style="width: 250px;" id="list2">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</body>
</html>
It looks like it was the way the options values were being added
So I changed this code and it worked.
function add_refdoc() {
var s = document.getElementById('list1')
var t = document.getElementById('input1').value
s.options[s.options.length] = new Option(t, t)
}

change value upon select

what i'm aiming is to show the other div when it selects one of the two options
Full time and Part Time
and if possible compute a different value for each
When the user selects Part time
the value of PrcA will change to PrcB
this is the code i used
<!====================================================================================>
<script language="javascript">
<!--//
function dm(amount)
{
string = "" + amount;
dec = string.length - string.indexOf('.');
if (string.indexOf('.') == -1)
return string + '.00';
if (dec == 1)
return string + '00';
if (dec == 2)
return string + '0';
if (dec > 3)
return string.substring(0,string.length-dec+3);
return string;
}
function calculate()
{
QtyA = 0;
TotA = 0;
PrcA = 1280;
PrcB = 640;
if (document.form1.qtyA.value > "")
{ QtyA = document.form1.qtyA.value };
document.form1.qtyA.value = eval(QtyA);
TotA = QtyA * PrcA;
document.form1.totalA.value = dm(eval(TotA));
Totamt =
eval(TotA) ;
document.form1.GrandTotal.value = dm(eval(Totamt));
}
//-->
</script>
<!====================================================================================>
<p>
<label for="acct" style="margin-right:90px;"><strong>Account Type<strong><font color=red size=3> * </font></strong></label>
<select name="acct" style="background-color:white;" class="validate[custom[serv]] select-input" id="acct" value="">
<option value="Full Time">Full-Time</option>
<option value="Part Time">Part-Time</option>
<option selected="selected" value=""></option>
</select></p>
<!====================================================================================>
<script>
$(document).ready(function() {
$("input[name$='acct']").select(function() {
var test = $(this).val();
$("div.desc").hide();
$("#acct" + test).show();
});
});
</script>
<!====================================================================================>
<p>
<table><tr><td>
<lable style="margin-right:91px;"># of Agent(s)<font color=red size=3> * </font></lable>
</td><td>
<input style="width:25px; margin-left:5px;" type="text" class="validate[custom[agnt]] text-input" name="qtyA" id="qtyA" onchange="calculate()" />
</td><td>
<div id="acctFull Time" class="desc">
x 1280 =
</div>
<div id="acctPart Time" class="desc" style="display:none">
x 640 =
</div>
</td><td>
$<input style="width:80px; margin-left:5px;" type="text" readonly="readonly" name="totalA" id="totalA" onchange="calculate()" />
</p>
</td></tr></table>
is there any way for me to achieve this?
Check this [FIDDLE] ..
Added two classes to the div's which show the amount.. This should make like easier to access them..
$(document).ready(function() {
$("#acct").on('change', function() {
var selVal = $(this).val();
if (selVal == '1') { // Full Time
$('.parttime').hide();
$('.fulltime').show();
$('.agent').show();
$('.error').hide();
}
else if (selVal == '2') { // Part Time
$('.parttime').show();
$('.fulltime').hide();
$('.agent').show();
$('.error').hide();
}
else {
$('.parttime').hide();
$('.fulltime').hide();
$('.agent').hide();
$('.error').show();
}
});
$('#qtyA').on('change', function() {
var selVal = $("#acct").val();
if (!isNaN($(this).val())) {
var total = 0;
if (selVal == '1') {
total = parseInt($(this).val()) * 1280;
}
else if (selVal == '2') {
total = parseInt($(this).val()) * 640;
}
$('#totalA').val(total.toFixed(2));
}
else {
$(this).val('0');
$('#totalA').val('0.00');
}
});
});​
Also you can completely eliminate the vanilla javascript and go with jQuery that should be lot easier..
got the answer this is what i used
<script type="text/javascript">
$(document).ready(function(){
$('#acct').change(function() {
$('.box').hide();
$('#acct' + $(this).val()).show();
});
});
</script>
A jsfiddle would help tremendously here. However, it sounds like you're trying to:
Show/hide content containers based on a pulldown selection, and
Process a field value based on the pulldown selection.
These two problems could generally be addressed like so (assuming jQuery, per your snippit):
<select id="time-select">
<option value="full">Full-Time</option>
<option value="part">Part-Time</option>
</select>
<div id="full-detail" class="detail">
Full-time info.
</div>
<div id="part-detail" class="detail">
Part-time info.
</div>
<input type="text" id="computed-value"/>
<script>
$(function() {
"use strict";
function computeValueBasedOn( opt ) {
// Evaluate the computed value here...
return opt ? "do" : "stuff";
}
$("#time-select").change(function(evt) {
$(".detail").hide();
$("#"+ this.value +"-detail").show();
$("#computed-value").val( computeValueBasedOn( this.value ) );
});
});
</script>

Categories

Resources