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);.
Related
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.
I need the total price from ( the base value + logo value + material value )
I had tried this code mycode
condition
1) if select the logo type and material type i need to get the total value.
2) if i selected both the value, now am changing the logo value i need to get the correct total
3) total to be displayed after selecting each option dynamical
4) no submit button to be used.
HTML
<p class="logotype left customLabel"><span>base price :</span>1000</p>
<p class="logotype left customLabel"><span>Logo Type :</span></p>
<form class="left margin0" name="logotypeform" method="post">
<select name="logoprice" id="logotypeprice">
<option value="">--</option>
<option value="50">Default logo</option>
<option value="100">Imported logo</option>
<option value="25">Text</option>
<option value="0">None</option>
</select>
</form>
<input class="logoTypeVal" type="" value="">
<p class="Material left customLabel"><span>Material :</span></p>
<form class="left margin0" name="priceform" method="post">
<select name="price" id="materialprice">
<option value="">--</option>
<option value="10">Nylon</option>
<option value="20">Sticker</option>
<option value="30">Printed</option>
<option value="30">Embroiding</option>
<option value="0">None</option>
</select>
</form>
<input class="materialVal" type="" value="">
<p class="Material left customLabel"><span>Total Value :</span></p><input class="totalVal" type="" value="total value">
JS
jQuery(document).ready(function(){
var baseValue = 1000;
jQuery('#logotypeprice').change(function(){
var logotypeprice = jQuery(this).val();
jQuery('input.logoTypeVal').val(logotypeprice);
});
jQuery('#materialprice').change(function(){
var materialprice = jQuery(this).val();
jQuery('input.materialVal').val(materialprice);
var baseprice = "<?php echo $basePrice ?>";
var logoval = logotypeprice;
var totalprice = parseInt(baseValue) + parseInt(materialprice) + parseInt(logoval);
alert(totalprice);
jQuery('input.totalVal').val(totalprice);
});
});
Update:
Since you need the total value to update based on changing each select you should calculate the total on both handlers. Like below
var baseValue = 1000,
logotypeprice = 0,
materialprice = 0;
$(document).ready(function () {
$('#logotypeprice').change(function () {
logotypeprice = jQuery(this).val();
$('input.logoTypeVal').val(logotypeprice);
calculateTotal();
});
$('#materialprice').change(function () {
materialprice = $(this).val();
$('input.materialVal').val(materialprice);
calculateTotal();
});
});
function calculateTotal() {
var totalprice = parseInt(baseValue) + parseInt(materialprice) + parseInt(logotypeprice);
$('input.totalVal').val(totalprice);
}
Here is an updated demo
PS: Instead of writing jQuery for each element you can use the short version $
You are trying to access logotypeprice variable which is not accessible inside materialprice change handler
Either declare logotypeprice globally like this
var baseValue = 1000;
var logotypeprice;
jQuery('#logotypeprice').change(function(){
logotypeprice = jQuery(this).val();
jQuery('input.logoTypeVal').val(logotypeprice);
});
jQuery('#materialprice').change(function(){
var materialprice = jQuery(this).val();
jQuery('input.materialVal').val(materialprice);
var baseprice = "100";
var logoval = logotypeprice;
var totalprice = parseInt(baseValue) + parseInt(materialprice) + parseInt(logoval);
alert(totalprice);
jQuery('input.totalVal').val(totalprice);
});
Or
access logo value from input.logoTypeVal or #logotypeprice value like this
jQuery('#materialprice').change(function(){
var materialprice = jQuery(this).val();
jQuery('input.materialVal').val(materialprice);
var baseprice = "100";
var logoval = jQuery('input.logoTypeVal').val(); // OR logoval = jQuery('#logotypeprice').val();
var totalprice = parseInt(baseValue) + parseInt(materialprice) + parseInt(logoval);
alert(totalprice);
jQuery('input.totalVal').val(totalprice);
});
Here is a demo
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
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
In my html file I have 2select boxes and 4 input text boxes.
From the first select you can choose how many numbers (textboxes) would you like to use.
From the second select you can choose a mathematical operation (+,-,*,/)
According to users choice in first select, number of input boxes will appear.
Now you add numbers to these inputs and based on what you have selected and what you have in inputs, the result should appear in a particular div.
Then, when I change anything the result should be updated.
This is what I have so far:
First select:
<select id="quantity" name="qua" onchange="selectQuantity(this.value)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
first select js:
function selectQuantity(selectedValue){
var e = document.getElementById("quantity");
var quantity = e.options[e.selectedIndex].value;
if ( quantity==='1') {
$('#nt').fadeIn();
} else if ( quantity==='2') {
$('#nt').fadeIn();
$('#nt1').fadeIn();
} else if ( quantity==='3') {
$('#nt').fadeIn();
$('#nt1').fadeIn();
$('#nt2').fadeIn();
} else {
$('#nt').fadeIn();
$('#nt1').fadeIn();
$('#nt2').fadeIn();
$('#nt3').fadeIn()
}
}
Second select html:
<select id="operation" name="ope" onchange="selectOperation(this.value)">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
Second select js:
function selectOperation(selectedValue){
var e = document.getElementById("operation");
var operation = e.options[e.selectedIndex].value;
}
Input text example:
<input type="text" id="nt" onchange="checkField(this.value)">
js:
function checkField(val)
{
}
And the result div:
<div id="result"></div>
So, where and how should I put my calculations to achieve this dynamicly updated result? To a separate function?
All of my js functions are in separate js file.
Thank you.
-FIDDLE example
Here is a suggestion:
function calculator() {
var val1 = parseInt($('#quantity').val());
var op = $('#operation').val();
for (var i = 0; i < val1; i++) {
var incr = i ? i : '';
$('#nt' + incr).fadeIn();
}
var sum = 0;
function values2() {
var internalSum = 0;
$('[id^="nt"').each(function () {
internalSum += parseInt(this.value == '' ? 0 : this.value);
});
return internalSum;
}
switch (op) {
case '+':
sum = val1 + values2();
break;
case '-':
sum = val1 - values2();
break;
case '*':
sum = val1 * values2();
break;
case '/':
sum = val1 / values2();
break;
default:
console.log('Missing parameters');
}
$('#result').html(sum);
}
$('select, input').on('change', calculator);
Demo