change event in jquery - javascript

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

Related

Jquery send result of SUM to div

I want to:
Get value from select, sum with other values, and place it inside a span.
Can I send the result of a value to a div/span without having to submit with a button? Is that possible?
please look at my fiddle: https://jsfiddle.net/groseler/3mq1ye1y/
HTML
$(function () {
$("#field16-1").change(function() {
var val = $(this).val();
var comEx = "150";
var youngDriver = "100";
var resultSum = parseInt(val, 10) + parseInt(comEx, 10) + parseInt(youngDriver, 10);
});
$("#result").html(resultSum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="field16-1">
<option value="">Please select...</option>
<option value="120">120</option>
<option value="230">230</option>
<option value="260">260</option>
</select>
<div>
Result should appear here ---> <span id="result" ></span></div>
Your code works after a bit change. You have only some typo. You need to add the $("#result").html(resultSum) into the change callback.
You don't need to submit anything. Submit is for the forms and after submitting the data almost always go to the server side code
$(function () {
$("#field16-1").change(function() {
var val = $(this).val();
var comEx = "150";
var youngDriver = "100";
var resultSum = parseInt(val, 10) + parseInt(comEx, 10) + parseInt(youngDriver, 10);
$("#result").html(resultSum);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="field16-1">
<option value="">Please select...</option>
<option value="120">120</option>
<option value="230">230</option>
<option value="260">260</option>
</select>
<div>
<span id="result" ></span></div>
Put $("#result").html(resultSum); inside the function
$(function () {
$("#field16-1").change(function() {
var val = $(this).val();
var comEx = "150";
var youngDriver = "100";
var resultSum = parseInt(val, 10) + parseInt(comEx, 10) + parseInt(youngDriver, 10);
$("#result").html(resultSum);
});
});
JSFIDDLE
The mistake you have done is that you put $("#result").html(resultSum); this outside the change event of dropdown.
Move $("#result").html(resultSum); statement to within .change() so the the sum can be changed every time the value of the select element changes.
$(function () {
$("#field16-1").change(function() {
var val = $(this).val();
var comEx = "150";
var youngDriver = "100";
var resultSum = parseInt(val, 10) + parseInt(comEx, 10) + parseInt(youngDriver, 10);
$("#result").html(resultSum);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="field16-1">
<option value="">Please select...</option>
<option value="120">120</option>
<option value="230">230</option>
<option value="260">260</option>
</select>
<div>
Result should appear here ---> <span id="result" ></span></div>

Jquery option:selected not working

I am trying to grab the selected option from the color but each time it returns the blank. When it goes to the cart page after it adds it to the car it returns the blank and not the selected color option.
// Adds items to the shopping cart
handleAddToCartForm: function() {
var self = this;
self.$formAddToCart.each(function() {
var $form = $(this);
var $product = $form.parent();
var price = self._convertString($product.data("price"));
var name = $product.data("name");
//Problem here
var color1 = $("#color1 option:selected").val();
$form.on("submit", function() {
var qty = self._convertString($form.find(".qty").val());
var subTotal = qty * price;
var total = self._convertString(self.storage.getItem(self.total));
var sTotal = total + subTotal;
self.storage.setItem(self.total, sTotal);
self._addToCart({
product: name,
price: price,
qty: qty,
color1: color1
});
var shipping = self._convertString(self.storage.getItem(self.shippingRates));
var shippingRates = self._calculateShipping(qty);
var totalShipping = shipping + shippingRates;
self.storage.setItem(self.shippingRates, totalShipping);
});
});
},
<div class="product-description" data-name="Rainbow" data-price="12">
<h3 class="product-name">Rainbow</h3>
<p class="product-price">$ 12</p>
<p class="select-color">Color 1:
<select id="color1">
<option value="blank"></option>
<option value="white">White</option>
<option value="red">Red</option>
<option value="orange">Orange</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="purple">Purple</option>
<option value="pink">Pink</option>
<option value="black">Black</option>
</select>
</p>
You need to get the color inside the submit event handler. You are currently trying to do it before user has changed anything
Change
var color1 = $("#color1 option:selected").val();
$form.on("submit", function() {
To
$form.on("submit", function() {
// get color when user submits . Need to also do some validation
var color1 = $("#color1 option:selected").val();

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