Show field based on selection (JS) - javascript

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.

Related

Adding values of dynamically created inputs [javascript]

I am creating my first bigger .js project from scratch and I'm completely stuck on one part. I am really new to web-dev and .js is my first programming language that I am learning. I want to create a dynamic calculator that allows for additional inputs to be added on button click. All that functionality is working however I do not know how to save and add values of all created inputs and then display their results added together.
My code only works for the first added input row, however even though each next input item has updated dynamic ID I do not know how to extract their values and use it in my function.I am assuming that arrays should play a big role in this, but it is just beyond my scope of understanding for now. I apologize if the code is a mess I am really into programming but this is only my first month. I would really appreciate all the help you can give.
function addItems() {
idIndex = idIndex + 1;
let newItem1 = document.createElement("div");
newItem1.innerHTML =
`<select id="select_euro${idIndex}" class="input_itemA input_item_new">
<option value="E6" class="option1">Euro 6</option>
<option value="E5" class="option2">Euro 5</option>
<option value="E4" class="option3">Euro 4</option>
<option value="E3" class="option4">Euro 3</option>
<option value="E2" class="option5">Euro 2</option>
<option value="E1" class="option6">Euro 1</option>
</select> ` +
`<input type="number" min="0" oninput="this.value =
!!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null" name="number_of_trucks" placeholder="L. Ciężarówek" id="input_item_truck${idIndex}" class="input_itemA input_item_new">
` +
`<select id="input_item_dmc${idIndex}" class="input_itemA input_item_new">
<option value="A" class="optionA">7,5t do 12t</option>
<option value="B" class="optionB">12 do 18t</option>
<option value="C" class="optionC">> 18t z 3 osi</option>
<option value="D" class="optionD">> 18t z 4 lub więcej osi</option>
</select>` +
`<input type="number" min="0" oninput="this.value =
!!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null" name="number_of_km" placeholder="Przejechane km" id="input_item_km${idIndex}" class="input_itemA input_item_new">
` +
`<button type="button" id="remove_input${idIndex}" class="btn_new_negative" onclick = remover()>-</button>`;
newItem1.setAttribute("id", "input_item" + idIndex);
newItem1.setAttribute("class", "input_item_new");
inputs.appendChild(newItem1);
let truckNoNew = document.querySelector(`#input_item_truck` + `${idIndex}`);
let euroClassNew = document.querySelector(`#select_euro` + `${idIndex}`);
let dmcNew = document.querySelector(`#input_item_dmc` + `${idIndex}`);
let truckKmNew = document.querySelector(`#input_item_km` + `${idIndex}`);
let span = document.querySelector("#result");
function calcTruckNew() {
if ((euroClassNew.value === "E6") & (dmcNew.value === "A")) {
let moneyAmount = truckKmNew.value * 0.014 * 11;
let resultNew = parseInt(moneyAmount * parseInt(truckNoNew.value));
span.textContent = resultNew;
} else if ((euroClassNew.value === "E6") & (dmcNew.value === "B")) {
let moneyAmount = truckKmNew.value * 0.002 * 11;
let resultNew = parseInt(moneyAmount * parseInt(truckNoNew.value));
span.textContent = resultNew;
} else if ((euroClassNew.value === "E6") & (dmcNew.value === "C")) {
let moneyAmount = truckKmNew.value * 0.004 * 11;
let resultNew = parseInt(moneyAmount * parseInt(truckNoNew.value));
span.textContent = resultNew;
} else if ((euroClassNew.value === "E6") & (dmcNew.value === "D")) {
let moneyAmount = truckKmNew.value * 0.005 * 11;
let resultNew = parseInt(moneyAmount * parseInt(truckNoNew.value));
span.textContent = resultNew;
}
}
btnCalc.addEventListener("click", calcTruckNew);
}
bntAdd.addEventListener("click", addItems);
//removes added inputs
function remover() {
btnRem = document.getElementById("remove_input" + idIndex);
newItem = document.getElementById("input_item" + idIndex);
newItem.parentNode.removeChild(newItem);
idIndex--;
}

How Would I get the value that is displayed in output, and set it as a variable?

How Would I get the value that is displayed in output, and set it as a variable so that way I can multiply it by another variable?
let calculate = () => {
let box1_selection = getValueById("pattern");
let box2_selection = getValueById("thick");
if (box1_selection == "" || box2_selection == "") {
document.getElementById("output").innerHTML = "Please select both values";
} else {
let value = "not specified";
/*if(box2_selection == 0 && box3_selection == 0 {
value = "$27.00";
} else if(box2_selection == 0 && box3_selection == 1) {
value = "$17.00";
}*/
var lolm = getPrice(box1_selection, box2_selection);
document.getElementById("output").innerHTML = lolm;
}
}
var getValueById = (id) => {
var selection = document.getElementById(id);
return selection.options[selection.selectedIndex].value;
}
var getPrice = (value_1, value_2) => {
// price_data is a 3 dimensional array.
var price_data = [
[
[8.00],
[13.50]
],
[
[20.80],
[22.05]
],
[
[53.10],
[99]
],
[
[20.20],
[99]
],
[
[24.00],
[99]
],
[
[99],
[99]
],
[
[15.23],
[99]
]
];
return price_data[value_1][value_2];
var roundedvalue1 = Math.ceil(document.getElementById('box3').value);
var roundedvalue2 = Math.ceil(document.getElementById('box4').value);
if (roundedvalue1 % 2 != 0) {
roundedvalue1 += 1;
}
if (roundedvalue2 % 2 != 0) {
roundedvalue2 += 1;
}
var result = document.getElementById('result');
var rounded1plus2 = (roundedvalue1 + 2)
var rounded2plus2 = (roundedvalue2 + 2)
var squareFoot = (rounded1plus2 * rounded2plus2 / 144)
var myResult = +lolm;
result.value = myResult;
}
<select id="pattern" onchange="calculate()">
<option value="">Select Glass Pattern</option>
<option value="0">Clear</option>
<option value="1">Starphire</option>
<option value="2">Bamboo</option>
<option value="3">Rain</option>
<option value="4">Satin Etch</option>
<option value="5">MasterCarre</option>
<option value="6">Rolled Glue Chip</option>
</select>
<select id="thick" onchange="calculate()">
<option value="">Select Glass Thickness</option>
<option value="0">3/8 (10mm)</option>
<option value="1">1/2 (12mm)</option>
</select>
<td><input id="box3" type="text" oninput="calculate()" placeholder="Whole #'s" maxlength="3" size="4" /></td>
<td><input id="box4" type="text" oninput="calculate()" placeholder="Whole #'s" maxlength="3" size="4" /></td>
<td><b>$</b><input id="result" maxlength="4" size="4" />Flat</td>
<br>
<div id="output">Please select both values</div>
<div>
</div>
Essentially what I'm looking to do is to grab the output that is displayed on the webpage as actual text, set is equal to a variable that changes with the selection, that I can multiply by other variables in other parts of the script.
I'm not fully understanding what you want. Here's my solution, if that helps.
You're already getting the output value in this line
var lolm = getPrice(box1_selection, box2_selection);`
It's already set to lolm. You can manipulate is as you like.
You've declared lolm inside the calculate arrow function as var lolm. So it's function scoped, if you want to access it outside the function (to use it in other functions) declare the variable lolm globally (outside the function).

How to use class names?

I have an issue with something. I have 2 lists of options.
Every option in one list has a name of M, every option in the other has a name of R.
I need to select certain options, say 'A' and 'C' from both lists. I need to add an 'X' bonus to the 'X' options, and a 'Y' bonus to the 'Y' options ('B').
The bonus is in the form of a percentage
So the problem is, how do I select those options, and add the bonus? Can it be done? I have been told class names can solve it, but how do I do that?
<form action="">
<fieldset>
<head>
<script type="text/javascript">
function myFunction() {
/*Left flank bonus*/
var MLef1 = document.getElementById("MeleeL").value;
var RLef1 = document.getElementById("RangedL").value;
var ML = MLef1 - 0;
var RL = RLef1 - 0;
/*Melee total*/
var MT1 = ML;
var MT2 = MT1 / 100;
var MT = MT2 - 0;
/*Ranged total*/
var RT1 = RL;
var RT2 = RT1 / 100;
var RT = RT2 - 0;
/*Left flank normal*/
/*Left flank melee*/
var x = document.getElementById("Melee").selectedIndex;
var y = (document.getElementsByTagName("option")[x].value);
var xy = document.getElementById("LM1").value;
/*Left flank Ranged*/
var p = document.getElementById("Ranged").selectedIndex;
var o = (document.getElementsByName("LR")[p].value);
var i = document.getElementById("LM1").value;
/*Ranged*/
var c1 = o * i;
var c = c1 - 0;
var RTZ = RT * c;
var RTz = RTZ - 0;
/*Melee*/
var z2 = y * xy;
var z = z2 - 0;
var MTZ = MT * z;
var MTz = MTZ - 0;
/*Zero function*/
if (MT <= 0) {
(document.getElementById("result").innerHTML = z);
}
else if (MT > 0) {
(document.getElementById("result").innerHTML = MTz);
}
if (RT <= 0) {
(document.getElementById("result1").innerHTML = c);
}
else if (RT > 0) {
(document.getElementById("result1").innerHTML = RTz);
}
}
</script>
<legend align="center" id="Defense">Defense</legend>
<table>
<tr>
<th>Left Flank</th>
<th>
<th>
<th>Center Flank</th>
<th>Right Flank</th>
</tr>
<tr>
<td>
<label>X Bonus</label>
<br>
<label>Y bonus</label>
<br>
</td>
<td>
<input type="number" id="MeleeL">%
<br>
<input type="number" id="RangedL">%
<br>
</tr>
</table>
<select id="Melee">
<option value="11">A</option>
<option value="9">B</option>
<option value="6">C</option>
</select>
<input type="number" style="width:50px" id="LM1">
<select id="Ranged">
<option name="LR" value="17">A</option>
<option name="LR" value="4">B</option>
<option name="LR" value="36">C</option>
</select><br>
<button type="button" id="buton" onclick="myFunction()">Calculate</button><br>
<p id="result">The Melee, </p><p id="result1">The R, </p>
</fieldset>
</form>
This amount varies, and will be inputed through a input box. Again, I need the user to be able to add a variable bonus to some, but not all, of the options in a list.
Thanks for all the help!
I found out, using trial, error, and a couple hours reading coding manuals, how to do this. I am now using "data-name1". It helps a lot.
<script>
document.getElementById("selectElement").selectedIndex = -1; // so that no option //is selected when the page is loaded
// Good!!!
function getData(){
var e = document.getElementById("qwert"); // get the <select> element
// Understood
var data_name1 = e.options[e.selectedIndex].dataset.name1; // get the selected //<option> and its name1 data attribute
// var data_name2 = e.options[e.selectedIndex].dataset.name2; get the selected //<option> and its name2 data attribute
var value = e.options[e.selectedIndex].value; // get the value of the selected <option>
//Result
document.getElementById("data1").innerHTML = data_name1;
document.getElementById("value").innerHTML = value;
}
</script>
<select id="qwert" onclick="getData ()">
<option value="135" data-name1="M">Halberdier</option>
<option value="150" data-name1="R">Lancer</option>
<option value="51" data-name1="R">Longbowman</option>
<option value="27" data-name1="M">Militia</option>
</select>
<p>
<label>data-name1 = </label>
<span>"</span><span id="data1"></span><span>"</span>
</p>
<p>
<label>value = </label>
<span>"</span><span id="value"></span><span>"</span>
</p>
Thanks for all the help, sorry about being unclear.
All the best

reset a drop down list value to previous value

I am using javascript to validate some drop down list selections. One selection is for the length of a buildings frame. The other 3 drop down are for garage doors that can be added to the side. I have the code alerting me if the total door widths have exceeded the frame length. I need the if condition to take the previous value of the last selected door drop down list and reset it to the amount before it if the amount exceeds my conditions in my if statement.
This is my html
Frame Length:
<select id="framewidth" onchange="doorsrightsideFunction()">
<option value="20">21</option>
<option value="25">26</option>
<option value="30">31</option>
<option value="35">36</option>
<option value="40">41</option>
</select>
<br>
<input type="hidden" name="eight_by_seven_width_right_side"
id="eight_by_seven_width_right_side" value="8">
<br>
<input type="hidden" name="eight_by_seven_height_right_side"
id="eight_by_seven_height_right_side" value="7">
<br>8x7:
<select id="eight_by_seven_right_side" onchange="doorsrightsideFunction()">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br>
<input type="hidden" name="nine_by_seven_width_right_side"
id="nine_by_seven_width_right_side" value="9">
<br>
<input type="hidden" name="nine_by_seven_height_right_side"
id="nine_by_seven_height_right_side" value="7">
<br>9x7:
<select id="nine_by_seven_right_side" onchange="doorsrightsideFunction()">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br>
<input type="hidden" name="ten_by_eight_width_right_side"
id="ten_by_eight_width_right_side" value="10">
<br>
<input type="hidden" name="ten_by_eight_height_right_side"
id="ten_by_eight_height_right_side" value="8">
<br>10x8:
<select id="ten_by_eight_right_side" onchange="doorsrightsideFunction()">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
This is my javascript so far
function doorsrightsideFunction() {
function getValue(idElement) {
return document.getElementById(idElement).value;
}
var eightwidth = getValue("eight_by_seven_width_right_side");
var ninewidth = getValue("nine_by_seven_width_right_side");
var tenwidth = getValue("ten_by_eight_width_right_side");
var eightwidthamount = getValue("eight_by_seven_right_side");
var ninewidthamount = getValue("nine_by_seven_right_side");
var tenwidthamount = getValue("ten_by_eight_right_side");
var framewidth = getValue("framewidth");
var totaldoorwidth;
var totaldooramount;
var framewidthtotaldoorwidth;
var framespace;
totaldoorwidth = eightwidth * eightwidthamount
+ ninewidth * ninewidthamount
+ tenwidth * tenwidthamount;
totaldooramount = parseInt(eightwidthamount, 10)
+ parseInt(ninewidthamount, 10)
+ parseInt(tenwidthamount, 10);
framewidthtotaldoorwidth = framewidth - totaldoorwidth;
framespace = totaldooramount + 1;
if (framewidthtotaldoorwidth < framespace) {
alert("You have to many doors on the right side");
} else { }
}
here is a link to my fiddle http://jsfiddle.net/steven27030/M52Hf/
http://jsfiddle.net/M52Hf/84/
you could use the data attribute and be sure to pass in the current element as a parameter on your doorsrightsideFunction call:
<select id="framewidth" onchange="doorsrightsideFunction(this)">
var previousValue = currentelement.getAttribute("data-prev");
if(previousValue == null)
previousValue = currentelement[0].value;
You will need to store the previous value so you can switch back when necessary, and update the previous value after a successful change. I would use arrays in various places.
var prevValue = Array();
function doorsrightsideFunction() {
function getValue(idElement) {
return document.getElementById(idElement).value;
}
function setValue(idElement,val) {
return document.getElementById(idElement).value = val;
}
var ids = Array("eight_by_seven_right_side","nine_by_seven_right_side","ten_by_eight_right_side");
var widths = Array(
getValue("eight_by_seven_width_right_side"),
getValue("nine_by_seven_width_right_side"),
getValue("ten_by_eight_width_right_side")
);
var values = Array();
for(i=0;i<ids.length;i++) {
if (!prevValue[i]) { prevValue[i]=0; }
values[i] = getValue(ids[i]);
}
var framewidth = getValue("framewidth");
var totaldoorwidth = 0;
var totaldooramount = 0;
var framewidthtotaldoorwidth;
var framespace;
for(i=0;i<ids.length;i++) {
totaldoorwidth += values[i] * widths[i];
totaldooramount += parseInt(values[i], 10);
}
framewidthtotaldoorwidth = framewidth - totaldoorwidth;
framespace = totaldooramount + 1;
if (framewidthtotaldoorwidth < framespace) {
alert("You have to many doors on the right side");
for(i=0;i<ids.length;i++) { setValue(ids[i],prevValue[i]); }
} else {
prevValue = values;
}
}
updated fiddle
Edit: In answer to your follow on question in the comment:
is there a way to make it loop through and find the next size down that would work if they choose to many?
Yes, you can have it iterate the values to find one that fits, as long as the initial values are valid (in this case no doors is a perfect initial value). This also means you don't need to worry about storing any previous value.
I had some fun with this a took some liberties with your code.
First, a few changes in the HTMl:
for each element with an onChange, have it pass the element that was changed so we can tell which one to modify:
<select ... onchange="doorsrightsideFunction(this)">
change the IDs of the _width and _height hidden inputs so they are of the form <id of select element>_width (i.e. the width element for the select with id="eight_by_seven_right_side" should be "eight_by_seven_right_side_width" so you just need to take id + "_width" to find it)
wrap all of the door select elements in a <div id="doorchoices"> ... </div> so they can be found programmatically. This way adding a new door to the system is as simple as adding the select and height/width hidden inputs within the containing div, and the javascript finds and uses them automagically.
The javascript changes, I tried to comment inline:
//make ids and widths global to this page so we only have to construct it on page load
var ids;
var widths;
function getValue(idElement) {
var el = document.getElementById(idElement);
if (el) {
return parseInt(el.value);
} else {
return null;
}
}
function setValue(idElement, val) {
return document.getElementById(idElement).value = val;
}
window.onload = function () {
//construct id list from elements within the containing div when the page loads
ids = Array("framewidth");
widths = Array(null);
var container = document.getElementById("doorchoices");
var selections = container.getElementsByTagName("select");
var i;
for (i = 0; i < selections.length; i++) {
ids.push(selections[i].id);
// get each door's width from the _width element that matches the id
widths.push(getValue(selections[i].id + "_width"));
}
}
// el is the 'this' passed from the select that changed
function doorsrightsideFunction(el) {
console.log(widths);
console.log(ids);
var changedIndex = ids.indexOf(el.id);
//get all of the option elements of the changed select
var possibleValueEls = el.getElementsByTagName("option");
var values = Array();
var possibleValues = Array();
var framewidth;
var curValue;
var totaldoorwidth;
var totaldooramount;
var framewidthtotaldoorwidth;
var framespace;
var i;
function calcWidth() {
totaldoorwidth = 0;
totaldooramount = 0;
var i;
framewidth = values[0];
//start with 1 since index 0 is the frame width
for (i = 1; i < ids.length; i++) {
console.log(i + ")" + ids[i] + " " + values[i] + "(" + widths[i] + ")");
totaldoorwidth += values[i] * widths[i];
totaldooramount += parseInt(values[i], 10);
}
framewidthtotaldoorwidth = framewidth - totaldoorwidth;
framespace = totaldooramount + 1;
}
// get all possible values from the option elements for the select that was changed
for (i = 0; i < possibleValueEls.length; i++) {
possibleValues.push(parseInt(possibleValueEls[i].value));
}
// values should be increasing in order
possibleValues.sort();
// except framewidth should be decreasing
if (el.id == "framewidth") {
possibleValues = possibleValues.reverse()
};
// get the value of each element
for (i = 0; i < ids.length; i++) {
values[i] = getValue(ids[i]);
if (changedIndex == i) {
curValue = values[i]
};
}
calcWidth();
console.log(framewidthtotaldoorwidth);
console.log(framespace);
if (framewidthtotaldoorwidth < framespace) {
alert("You have to many doors on the right side");
// start with the current value and try each until it fits
for (validx = possibleValues.indexOf(curValue); validx >= 0, framewidthtotaldoorwidth < framespace; validx--) {
//change the value in the values array
values[changedIndex] = possibleValues[validx];
//change the select to match
setValue(el.id, possibleValues[validx]);
//see if it fits
calcWidth();
}
}
}
New fiddle
and the simplicity of adding another door size - just add this to the HTML:
<input type="hidden" name="twelve_by_ten_right_side_width" id="twelve_by_ten_right_side_width" value="12" />
<input type="hidden" name="twelve_by_ten_right_side_height" id="twelve_by_ten_right_side_height" value="10" />
<br />
<label for="twelve_by_ten_right_side">12x10:</label>
<select id="twelve_by_ten_right_side" onchange="doorsrightsideFunction(this)">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
New door fiddle

Cannot use text in option value with keyup function

I want be able to capture to name=formdesc an option value that is text and not numbers, but I need numbers to calculate price point below. Is there a way to change it, so that it calculates properly (below JS) and capture option values as text only instead numbers (HTML)?
Sample of what I need:
<select id="apparelType" name="formdesc">
<option selected="selected" value="na">Select</option>
<option value="tshirt">T-Shirt</option>
BUT Breakes my JS!
HTML: (what I have now)
<select id="apparelType" name="formdesc">
<option selected="selected" value="na">Select</option>
<option value="0">T-Shirt</option>
<option value="1">Shorts</option>
<option value="2">Hat</option>
<option value="3">Bag</option>
</select>
<input id="numb" type="number" name="formterm">
<id="tot"><Total: $0.00 >
JS:
<script type="text/javascript">// <![CDATA[
//
$(document).ready(function(){
$('#numb').keyup(function(){
var appVal = new Array();
appVal[0] = 15; <--[tshirt]
appVal[1] = 20;
appVal[2] = 25;
appVal[3] = 30;
var cost = 0;
var fmapVal = $('#apparelType').val();
if (fmapVal == 'na')
{ alert ('Please select an apparel type.');
}
else
{
cost = appVal[fmapVal];
};
//alert(cost);
var getNumb = $('#numb').val();
var baseTotal = cost * getNumb;
var getTax = baseTotal * .06;
var getTotal = baseTotal + getTax;
$('#tot').html('Total: $' + getTotal.toFixed(2));
$('#formbal').val(getTotal.toFixed(2));
});
});
// ]]></script>
<form>
<select id="apparelType" name="apparelType">
<option selected="selected" value="na">Select</option>
<option value="0">T-Shirt</option>
<option value="1">Shorts</option>
<option value="2">Hat</option>
<option value="3">Bag</option>
</select>
<label for="numb">Total: <span>$</span></label>
<input id="numb" type="number" name="formterm" value="0.00" >
<input id="pretaxTotal" type="hidden" value="0.00" >
<br>
<textarea id="formdesc" name="formdesc" rows="12" cols="20"></textarea>
</form>
<script type="text/javascript">
$('#apparelType').change(function(){
var apparelType = $('#apparelType');
var fmapVal = apparelType.val();
if (fmapVal == 'na') {
alert('Please select an apparel type.');
} else {
var appVal = [ 15, 20, 25, 30 ];
var description = apparelType.find('option:selected').text();
var cost = appVal[fmapVal];
var pretaxTotal = parseInt($('#pretaxTotal').val());
var subtotal = pretaxTotal + cost;
var updatedTotal = ( subtotal * 1.06 ).toFixed(2);
$('#pretaxTotal').val(subtotal);
$('#numb').val(updatedTotal);
$('#formdesc').append(description + '\n');
}
});
/* The following code is cosmetic. Makes dollar sign appear to be inside the input field */
$('label > span').css('position','relative').css('left','20px').css('font-size','80%');
$('input[type=number]').css('padding-left','15px');
</script>
If you need to take option name then val is not what you need. Instead try this:
var optionName = $('#apparelType').find('option:selected').text();
Hope I understood you correctly (although it's hard).
Could use a function with a case statement to get the cost from passed text strings:
function getVal(value) {
switch(value) {
case 'tshirt':
cost = 15;
break;
case 'shorts':
cost = 15;
break;
case 'hat':
cost = 15;
break;
case 'bag':
cost = 15;
break;
default:
cost = 'Please select an option...';
break;
}
return cost;
}
Then in your if statement use cost = getVal(fmapVal);.

Categories

Resources