Adding values of dynamically created inputs [javascript] - 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--;
}

Related

loop to check combination of dropdown & checkbox in pure javascript

Good morning!
I have a page with 1 dropdown menu that has 24 options to select.
As well There are 12 checkboxes to select.
Each dropdown option and each checkbox has a predefined variable.
i.e.:
dropdown value="utcValue0 -> var utc0 and
checkbox value id="gameCheck" -> var gameTag
desired output here is a new variable var a = utc0 + gameTag;
My current solution works, however it is very tedious and terrible to read and there must be a whole lot easier way to handle this. I'm at the moment just defining each scenario 1 by 1.
Considering it's 24 dropdown menus and 12 checkboxes this can not be the way..
I think it can be done with a smart nested loop, but I can't come up with how to actually write that.
I'd highly appreciate some help! Thank you so much!
<select name="hourSelector" id="hourSelectorID">
<option value="utcValue0">0 - 1 UTC</option>
<option value="utcValue1">1 - 2 UTC</option>
<option value="utcValue2">2 - 3 UTC</option>
<option value="utcValue3">3 - 4 UTC</option>
<option value="utcValue4">4 - 5 UTC</option>
<option value="utcValue5">5 - 6 UTC</option>
</select>
<input type="checkbox" class="custom-control-input" id="gameCheck">
<input type="checkbox" class="custom-control-input" id="purchCheck">
<input type="checkbox" class="custom-control-input" id="inputCheck">
var utc0 = 'something';
var utc1 = 'something';
var utc2 = 'something';
var utc3 = 'something';
var utc4 = 'something';
var utc5 = 'something';
//var utcX = 'created>"' + todayUTC + 'T00:00:00Z"' + ' ' + 'created<"' + todayUTC + 'T01:00:00Z"';
var gameTag = 'whatever';
var purchTag = 'otherwhatever';
var eventTag = 'morewhatver';
// grab input Hour
var hourDropdown = document.getElementById("hourSelectorID");
var selectedHour = hourDropdown.options[hourDropdown.selectedIndex].value;
if (document.getElementById('gameCheck').checked) {
if (selectedHour == 'utcValue0' ) {
var a = utc0 + eventTag
}
if (selectedHour == 'utcValue1') {
var a = utc1 + eventTag
}
if (selectedHour == 'utcValue2') {
var a = utc2 + eventTag
}
if (selectedHour == 'utcValue3') {
var a = utc3 + eventTag
}
if (selectedHour == 'utcValue4') {
var a = utc4 + eventTag
}
if (selectedHour == 'utcValue5') {
var a = utc5 + eventTag
}
}
You have changed your question so I'm not sure with what follows. Drop a comment below for adjustments or questions :-)
var formEl = document.getElementById("form");
var selectEl = document.getElementById("hourSelectorID");
var checkboxEls = Array.prototype.slice.call(
document.getElementsByClassName("custom-control-input")
);
// option elements
for (let i = 0; i < 24; i++) {
let optionEl = document.createElement("option");
optionEl.value = "utcValue" + i;
optionEl.textContent = i + " - " + (i + 1) + " UTC";
selectEl.appendChild(optionEl);
}
// form submit
formEl.addEventListener("submit", function (ev) {
ev.preventDefault();
console.log(toStringStuff());
});
// rename as needed :-)
function toStringStuff () {
var now = Date.now(); // in ms
var hourInMs = 1000 * 60 * 60;
var dayInMs = hourInMs * 24;
var today = now - now % dayInMs; // `now` with time set to 0
var i = selectEl.selectedIndex; // hours to add to `today`
var dt0 = new Date(today + i * hourInMs).toISOString();
var dt1 = new Date(today + (i + 1) * hourInMs).toISOString();
var utc = 'created>"' + dt0 + ' ' + 'created<"' + dt1;
return [utc].concat(checkboxEls.filter(
function (el) { return el.checked; }
).map(
function (el) { return el.value; }
)).join(" ");
}
<form id="form">
<select
id="hourSelectorID"
name="hourSelector"
></select>
<label><input
id="gameCheck"
type="checkbox"
class="custom-control-input"
value="gameTag"
checked
> Game Check</label>
<label><input
id="purchCheck"
type="checkbox"
class="custom-control-input"
value="purchTag"
checked
> Purch Check</label>
<input type="submit">
</form>
Here is a solution taking advantage of the options indexes matching the itteration of the string. It takes the index of the selected option and changes the string accordingly while concatenating the values from selected checkboxes.
let dateUTC = new Date();
let todayUTC = dateUTC.getUTCFullYear() + '-' + (('0' + dateUTC.getUTCMonth()+1)).slice(-2) + '-' + ('0' + dateUTC.getUTCDate()).slice(-2);
const select = document.querySelector("#hourSelectorID");
const allCheckboxes = document.querySelectorAll('input[name="chkBox"]');
const elements = [...allCheckboxes, select]
elements.forEach(el => {
el.addEventListener("change", () => {
let checkedValues = []
const checked = [...allCheckboxes].filter(cb => cb.checked);
checked.forEach(cb => checkedValues.push(cb.value))
console.log(`created>" ${todayUTC} T0${select.selectedIndex}:00:00Z" created<" ${todayUTC} T0${select.selectedIndex+1}:00:00Z" ${checkedValues.join(' ')}`)
});
});
<select name="hourSelector" id="hourSelectorID">
<option value="utcValue0">0 - 1 UTC</option>
<option value="utcValue1">1 - 2 UTC</option>
<option value="utcValue2">2 - 3 UTC</option>
<option value="utcValue3">3 - 4 UTC</option>
<option value="utcValue4">4 - 5 UTC</option>
<option value="utcValue5">5 - 6 UTC</option>
</select>
<input value="whatever" type="checkbox" name="chkBox" class="custom-control-input" id="gameCheck">
<input value="otherwhatever" type="checkbox" name="chkBox" class="custom-control-input" id="purchCheck">
<input value="morewhatver" type="checkbox" name="chkBox" class="custom-control-input" id="inputCheck">

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.

implement cost for select items then total

I am still trying to dissect this code that I got from here, works great but I need to implement a cost amount into it as well.
I have the script setup to do price * qty, but I am trying to figure out how to do price - cost * qty.
I am new to scripting and am trying to figure this out
this is how the html looks
<select name="item" id="item" size="1">
<option value="">Device</option>
<option value="200.00">iPhone 4</option>
<option value="300.00">iPhone 4S</option>
<option value="450.00">iPhone 5</option>
<option value="300.00">Galaxy S3</option>
<option value="450.00">Galaxy S4</option>
<option value="450.00">Galaxy Note ll</option>
<option value="600.00">Galaxy Note lll</option>
<option value="700.00">Galaxy S5</option>
<option value="500.00">HTC One</option>
<option value="650.00">HTC One M8</option>
</select>
</div></td>
<td><div align="center">
<div align="center"><span id="price"></span></div>
</div></td>
<td height="43">
<div align="center"><span id="cost"></span></div>
</td>
<td>
<div align="center">
<input name="qty" type="Text" id="qty" size="2" maxlength="3"/>
</div>
</td>
<td>
<div align="center">
<span id="result"></span>
and this is what the script looks like.
var phones = document.getElementById('phones');
var phones1 = document.getElementById('phones1');
var phones2 = document.getElementById('phones2');
var phones3 = document.getElementById('phones3');
item.onchange = function() {
price.innerHTML = "$" + this.value;
qty.value = 1; //Order 1 by default.
add();
};
function add() {
var inputs = document.getElementsByTagName('input');
var selects = document.getElementsByTagName('select');
var total = 0;
var taxes = 0;
for (var i = 0; i < selects.length; i++) {
var sum = 0;
var price = (parseFloat(selects[i].value) )?parseFloat(selects[i].value):0;
var qty = (parseFloat(inputs[i].value) )?parseFloat(inputs[i].value):0;
sum += price * qty;
total += sum * 1.06
taxes += sum * 0.06
if(i == 0){
document.getElementById('result').innerHTML = "$" + sum;
}else{
document.getElementById('result'+i).innerHTML = "$" + sum;
}
};
document.getElementById('total').innerHTML = "$" + total.toFixed(2);
document.getElementById('taxes').innerHTML = "$" + taxes.toFixed(2);
}
is there a way, I can incorporate a second value in the option and use a reference to it in the script? I just can figure it out.
I did try adding a
<option value="200.00" value2="100">iPhone 4</option>
and then put it in the script like this
item.onchange = function() {
price.innerHTML = "$" + this.value;
cost.innerHTML = "$" - this.value;
qty.value = 1; //Order 1 by default.
add();
};
but it did not work
Try this way:
item.onchange = function() {
price.innerHTML = "$" + this.value;
cost.innerHTML = "$" + (-this[this.selectedIndex].getAttribute('value2'));
qty.value = 1; //Order 1 by default.
add();
};
And then modif add() in this way:
var cost = (parseFloat(selects[i][selects[i].selectedIndex].getAttribute('value2')) )?parseFloat(selects[i][selects[i].selectedIndex].getAttribute('value2')):0;
var qty = (parseFloat(inputs[i].value) )?parseFloat(inputs[i].value):0;
sum += (price - cost) * qty;
What you need to do is to use getAttribute() to get value2 and use .selectedIndex property to identify the selected option in the dropdown control.
Or at least this is my explanation.
It's working here

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