javascript - calculate on change of values - javascript

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

Related

Select values not correctly increasing/decreasing total number in js

I thought I had solved this javascript 'for' loop to sum up the numeric choices of several select fields to a number, each time one of them is changed.
But, modifying a choice in any of the selected fields is adding the number again, instead of replacing the initial choice number - which is what I want.
Example: a user chooses from 3 fields, these values: +15, -5, +1.
The total should be "11"
If the user modifies their first select to +10 instead of #+15, the total value should be "6". Instead, it's ADDING the modified number to everything. So the number becomes "21" - not what I want.
Note: I want to increase the number incrementally with each select choice - NOT a total of all of them when the user is done with the fields
Here's what I've got:
<form action="/cgi-bin/dropdown.cgi" method="post">
<select class="select0 selectables" id="dropdown-0" name="dropdown0">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="10">Choice 1 (+10)</option>
<option value="-5">Choice 2 (-5)</option>
<option value="60">Choice 3 (+60)</option>
</select>
<br />
<select class="select1 selectables" id="dropdown-1" name="dropdown1">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="8">Choice A (+8)</option>
<option value="-10">Choice B (-10)</option>
<option value="15">Choice C (+15)</option>
</select>
<br />
<select class="select2 selectables" id="dropdown-2" name="dropdown2">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="5">Choice ii (+5)</option>
<option value="15">Choice ii (+15)</option>
<option value="12">Choice iii (+12)</option>
</select>
</form>
<div id="tally" style="">0</div>
<script>
var sum = 0;
document.addEventListener("DOMContentLoaded", function(event) {
var gg1 = new JustGage({
id: "gg1",
value: 0,
textRenderer: customValue
});
var userSelection = document.getElementsByClassName('selectables');
for(let i = 0; i < userSelection.length; i++) {
userSelection[i].addEventListener("change", function() {
fieldvalue = userSelection[i].value;
fieldname = userSelection[i].id;
if (fieldvalue > 0) {
// using += breaks other scripts for some reason
sum = sum + parseInt(fieldvalue);
} else if (fieldvalue < 1) {
fieldvalue = fieldvalue * -1;
sum = sum - parseFloat(fieldvalue, 10);
}
document.getElementById("tally").innerHTML = sum;
// this is the value that takes the number I'm trying to increment based on choices in selects
gg1.refresh(sum);
return false;
})
}
});
</script>
This happens because inside the callback function of the change listener you're not considering the values of the other dropdowns. Grab them using a second for-loop and recalculate the sum.
Here's your modified callback function:
for (let i = 0; i < userSelection.length; i++) {
userSelection[i].addEventListener("change", function() {
sum = 0;
for (var b = 0; b < userSelection.length; b++) {
fieldvalue = userSelection[b].value;
if (fieldvalue > 0) {
// using += breaks other scripts for some reason
sum = sum + parseInt(fieldvalue);
} else if (fieldvalue < 1) {
fieldvalue = fieldvalue * -1;
sum = sum - parseFloat(fieldvalue, 10);
}
}
document.getElementById("tally").innerHTML = sum;
// this is the value that takes the number I'm trying to increment based on choices in selects
gg1.refresh(sum);
return false;
})
}
Whenever any of the select values is changed, you should re-compute the entire sum. Something like this:
onload = function {
var userSelection = document.getElementsByClassName('selectables');
for(let i = 0; i < userSelection.length; i++) {
userSelection[i].addEventListener("change", function() {
var sum= computeSum();
//whatever you want to do with sum
})
}
function computeSum() {
var sum = 0;
for(const select in userSelection) {
sum += select.value;
}
return sum;
}
}
Like others have mentioned, you need to recalculate the total every time any of select control value changes. Here's a demo (un-optimized):
document.querySelectorAll('select').forEach(select => select.addEventListener('change', (event) => {
if (allValid()) {
document.querySelector('#tally').innerHTML = calcTotal();
}
}))
const allValid = () => {
let status = true;
document.querySelectorAll('select').forEach(select => {
if (select.selectedIndex === 0) status = false;
})
return status;
}
const calcTotal = () => {
let total = 0;
document.querySelectorAll('select').forEach(select => {
total += parseInt(select.value);
})
return total;
}
<select class="select0 selectables" id="dropdown-0" name="dropdown0">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="10">Choice 1 (+10)</option>
<option value="-5">Choice 2 (-5)</option>
<option value="60">Choice 3 (+60)</option>
</select>
<br />
<select class="select1 selectables" id="dropdown-1" name="dropdown1">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="8">Choice A (+8)</option>
<option value="-10">Choice B (-10)</option>
<option value="15">Choice C (+15)</option>
</select>
<br />
<select class="select2 selectables" id="dropdown-2" name="dropdown2">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="5">Choice ii (+5)</option>
<option value="15">Choice ii (+15)</option>
<option value="12">Choice iii (+12)</option>
</select>
<div id="tally" style="">0</div>

Javascript Issue changing a form input

Thanks in advance.
I want to change the value of input text "total" in a form depending the value of the select "opciones". I tried with onchange(), with document.getElementById("").value but it doesn't works.
I dont know what is failing, but I cannot change the input value.
<form name="formulario">
<select name="opciones" id="opciones">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<input type="text" name="suma" id="total">
</form>
Javascript:
function formtotal() {
if (document.formulario.opciones.value = "1") {
document.formulario.suma.value = "1000";
}
else if (document.formulario.opciones.value = "2") {
document.formulario.suma.value = "1250";
}
else if (document.formulario.opciones.value = "3") {
document.formulario.suma.value = "1500";
}
}
I think you should try to work with
let e = document.getElementById("opciones");
let total = document.getElementById("total");
switch(e.selectedIndex) {
case 0:
total.value = 1000;
break;
case 1:
total.value = 1250;
break;
case 2:
total.value = 1500;
break;
default:
total.value = 0;
}
I think instead of document.formulario.suma.value it should be document.formulario.total.value.
However, below code is working fine. Tested in jsfiddle (link below).
function formtotal() {
var x = document.getElementById("opciones").value;
if (x == "1") {
document.getElementById("total").value = "1000";
}
else if (x == "2") {
document.getElementById("total").value = "1250";
}
else if (x == "3") {
document.getElementById("total").value = "1500";
}
}
Add onchange to the select tag as per below snippet:
<select name="opciones" id="opciones" onchange="formtotal()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
https://jsfiddle.net/fghxhtmk/ - Working fine. Please check.
EDIT: Added "value" to each option tag.
One clear mistake I can see is your use of the equality operator
document.formulario.opciones.value = "1"
Should be
document.formulario.opciones.value == "1"
Due to this, your first if statement is always going to be evaluated as true.

Count Unique Selection from Multiple Dropdown

I'm new to jquery, I'm working on a survey form and I have multiple dropdown menus for different questions but they all have the same dropdown value. Supposed I have:
<select name="Forms[AgentIsPitch]" id="Forms_AgentIsPitch">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<select name="Forms[MandatoryOptIsStated]" id="Forms_MandatoryOptIsStated">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
And other different dropdowns with different id's. What is the best way to count how many has selected Yes, No and N/A/ ? Thanks
you can do it simple this way
$('select').change(function() {
// get all selects
var allSelects = $('select');
// set values count by type
var yes = 0;
var no = 0;
// for each select increase count
$.each(allSelects, function(i, s) {
// increase count
if($(s).val() == 'Yes') { yes++; }
if($(s).val() == 'No') { no++; }
});
// update count values summary
$('.cnt-yes').text(yes);
$('.cnt-no').text(no);
});
DEMO
Try this — https://jsfiddle.net/sergdenisov/h8sLxw6y/2/:
var count = {};
count.empty = $('select option:selected[value=""]').length;
count.yes = $('select option:selected[value="Yes"]').length;
count.no = $('select option:selected[value="No"]').length;
count.nA = $('select option:selected[value="N/A"]').length;
console.log(count);
My way to do it would be :
var optionsYes = $("option[value$='Yes']:selected");
var optionsNo = $("option[value$='No']:selected");
var optionsNA = $("option[value$='N/A']:selected");
console.log('number of yes selected = ' + optionsYes .length);
console.log('number of no selected = ' + optionsNo .length);
console.log('number of N/A selected = ' + optionsNA .length);
Check the console (or replace with alert).
With your code, it would be something like that (assuming you want to check on a button click event) :
<select name="Forms[AgentIsPitch]" id="Forms_AgentIsPitch">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<select name="Forms[MandatoryOptIsStated]" id="Forms_MandatoryOptIsStated">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<button class="btn btn-primary" id="countYes"></button>
<script type="text/javascript">
$('#countYes').on('click', function(){
var optionsYes = $("option[value$='Yes']:selected");
var optionsNo = $("option[value$='No']:selected");
var optionsNA = $("option[value$='N/A']:selected");
console.log('number of yes selected = ' + optionsYes .length);
console.log('number of no selected = ' + optionsNo .length);
console.log('number of N/A selected = ' + optionsNA .length);
});
</script>
You can check at another event, I choosed a button click just for example.
There is likely a cleaner way to do this, but this will get the job done (assuming there is a button click to trigger things):
$("#theButton").on('click', function() {
var totalSelect = 0;
var totalYes = 0;
var totalNo = 0;
var totalNA = 0;
$("select").each(function(){
totalSelect++;
if ($(this).val() == "Yes") { totalYes++; }
if ($(this).val() == "No") { totalNo++; }
if ($(this).val() == "N/A") { totalNA++; }
});
});
Hope this helps the cause.
In common you can use change event:
var results = {};
$('select').on('change', function() {
var val = $(this).val();
results[val] = (results[val] || 0) + 1;
});
DEMO
If you want count for each type of select:
$('select').on('change', function() {
var val = $(this).val();
var name = $(this).attr('name');
if (!results[name]) {
results[name] = {};
}
results[name][val] = (results[name][val] || 0) + 1;
});
DEMO
In the results will be something like this:
{
"Forms[AgentIsPitch]": {
"Yes": 1,
"No": 2,
"N/A": 3
},
"Forms[MandatoryOptIsStated]": {
"No": 5,
"N/A": 13
},
}
UPD: for counting current choice:
$('select').on('change', function() {
var results = {};
$('select').each(function() {
var val = $(this).val();
if (val) {
results[val] = (results[val] || 0) + 1;
}
})
console.log(results);
});
DEMO

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