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
Related
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--;
}
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
Want to get the options in this example to work well, but I need some help/tips from you.
How to block selecting the desired options if the quantity is not selected.
Is there a way to auto-update/live-update the price/calculations for selected type of paper option when the quantity is changed?
Why in my example do I need to press double-click on the desired paper option button to re-calculate the correct price for subtotal? If I press it once the subtotal price is not changing.
You can check the demo and you will understand what I mean.
Demo: http://jsfiddle.net/c7b5f5t9/
I'm new to jQuery. Thank you in advance.
Html code:
<h3>Select Quantity:</h3>
<select name="quantity-select" id="quantity" onchange="subtotal()">
<option data-price="0.00" value="0" selected>Select Quantity</option>
<option data-price="1.49" value="55" >55 Flyers for 81.95$ / 1.49$ each</option>
<option data-price="1.39" value="66" >66 Flyers for 91.74$ / 1.29$ each</option>
<option data-price="1.29" value="77" >77 Flyers for 99.33$ / 1.09$ each</option>
<option data-price="1.19" value="88" >88 Flyers for 104.72$ / 0.89$ each</option>
</select>
<h3>Select Paper:</h3>
<ul class="paper">
<li data-price="0.00" onclick="subtotal()">Standard Paper<br>(+0.00$)</li>
<li data-price="0.15" onclick="subtotal()">Double Thick Paper<br>(+0.15$/piece)</li>
<li data-price="0.25" onclick="subtotal()">Triple Thick Paper<br>(+0.25$/piece)</li>
</ul>
<h3>Extra Options:</h3>
<input name="box1" value="nolaminating" id="nolaminating" data-price="0.00" type="radio" onchange="subtotal()">No Laminating (+0.00$)<br>
<input name="box1" value="matte" id="matte" data-price="50.00" type="radio" onchange="subtotal()">Matte Laminating (+50.00$)<br>
<input name="box1" value="gloss" id="gloss" data-price="75.00" type="radio" onchange="subtotal()">Gloss Laminating (+75.00$)<br>
<div class="prices">
<h3>Flyers = $<span class="sum" id="flyers">0.00</span></h3>
<h3>Paper = $<span class="sum" id="papertype">0.00</span></h3>
<h3>Extra Options = $<span class="sum" id="extraoptions">0.00</span></h3>
</div>
<h3>Subtotal = $<span id="subtotal">0.00</span></h3>
Script code:
var flyersprice = '0.00';
var paperoptions = '0.00';
var extraoptions = '0.00';
function subtotal(){
var price = $("#quantity option:selected").attr("data-price");
flyersprice = $("#quantity option:selected").val() * price;
$("#flyers").text(flyersprice.toFixed(2));
$(".paper li").click(function(){
var paperoptions = $(this).data("price") * $("#quantity option:selected").val();
$("#papertype").text(paperoptions.toFixed(2));
});
$('#papertype').change(subtotal);
$("input[type=radio]").change(function(){
var extraoptions = $(this).data("price");
$("#extraoptions").text(extraoptions);
});
$('input').change(subtotal);
var sum = 0;
$('.sum').each(function() {
sum += +$(this).text();
});
$("#subtotal").text(sum.toFixed(2));
}
How to block selecting the desired options if the quantity is not selected.
you don't need to do that, see demo below
Is there a way to auto-update/live-update the price/calculations for selected type of paper option when the quantity is changed?
yes, you have just to keep values of these inputs
Why in my example do I need to press double-click on the desired paper option button to re-calculate the correct price for subtotal? If I press it once the subtotal price is not changing.
this is normal, because you put two events on the same button "onclick" + "bind"
that's what you need to do
var selectedPaper = null;
function subtotal(){
var price= $("#quantity option:selected").attr("data-price");
if($("#quantity").val() == 0){
$("#papertype").text("0.00");
$("#extraoptions").text("0.00");
$("input[type=radio]").attr('checked',false)
selectedPaper = null;
}
flyersprice = $("#quantity").val() * price;
$("#flyers").text(flyersprice.toFixed(2));
var sum = 0;
$('.sum').each(function() {
sum += +$(this).text();
});
$("#subtotal").text(sum.toFixed(2));
}
$(function(){
$("#quantity").on('change',function(){
if(selectedPaper){
$(".paper li").eq(selectedPaper).trigger('click');
}
subtotal();
});
$(".paper li").on('click',function(){
if($("#quantity").val() != 0){
var paperoptions = $(this).data("price") * $("#quantity").val();
$("#papertype").text(paperoptions.toFixed(2));
selectedPaper = $(".paper li").index(this);
subtotal();
}else{
$("#papertype").text("0.00");
selectedPaper = null;
}
});
$("input[type=radio]").on('change',function(){
if($("#quantity").val() != 0){
var extraoptions = $(this).data("price");
$("#extraoptions").text(extraoptions);
subtotal();
}else{
$("#extraoptions").text("0.00");
selectedPaper = null;
}
});
})
This a DEMO
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
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);.