Calculate and Passing Value from select option to input box - javascript

I'm new to HTML and JavaScript. I need to do a website where it requires to sum up the Total value based on the select options. After that, pass the value back to the input in HTML.
HTML code
<select class="normalinput" name="giftname" id="giftname" onchange="populate('giftname')">
<option value="None">None</option>
<option value="G0001">Big Graduation Bear +RM60.00</option>
<option value="G0002">Small Graduation Bear +RM20.00</option>
<option value="G0003">Handcraft Gift Card +RM5.00</option>
<option value="G0004">Valentine Gift Card +RM10.00</option>
<option value="G0005">Godiva Chocolate Box +RM100.00</option>
<option value="G0006">Ferrero Rocher Love Box +RM90.00</option>
</select>
<p class="total"> Total: RM <input type="number" name="total" id="total"></p>
JavaScript Code
<script type="text/javascript">
function populate(giftname) {
var giftname = document.getElementById(giftname);
var gg = giftname.options[giftname.selectedIndex].value;
var total;
if (gg.value == "G0001") {
total = 90 + 60;
document.getElementById("total").value = total;
}
else if (gg.value == "G0002") {
total = 90 + 20;
document.getElementById("total").value = total;
}
else if (gg.value == "G0003") {
total = 90 + 5;
document.getElementById("total").value = total;
}
else if (gg.value == "G0004") {
total = 90 + 10;
document.getElementById("total").value = total;
}
else if (gg.value == "G0005") {
total = 90 + 100;
document.getElementById("total").value = total;
}
else if (gg.value == "G0006") {
total = 90 + 90;
document.getElementById("total").value = total;
}
else
total = 90;
document.getElementById("total").value = total;
}
</script>
A screenshot of result needed
Thank you so much.

You can add a data attribute to your HTML option elements to contain the price and use it to compute your total price.
<select class="normalinput" name="giftname" id="giftname" onchange="populate('giftname')">
<option data-price="0" value="None">None</option>
<option data-price="60" value="G0001">Big Graduation Bear +RM60.00</option>
<option data-price="20" value="G0002">Small Graduation Bear +RM20.00</option>
<option data-price="5" value="G0003">Handcraft Gift Card +RM5.00</option>
<option data-price="10" value="G0004">Valentine Gift Card +RM10.00</option>
<option data-price="100" value="G0005">Godiva Chocolate Box +RM100.00</option>
<option data-price="90" value="G0006">Ferrero Rocher Love Box +RM90.00</option>
</select>
<p class="total"> Total: RM <input type="number" name="total" id="total"></p>
<script type="text/javascript">
populate('giftname');
function populate(giftnameId) {
var giftnameSelect = document.getElementById(giftnameId); // Select dropdown
let selectedOption = giftnameSelect.options[giftnameSelect.selectedIndex]; // Selected option
// Get the selected value. We need the plus to parse it to a number, because initially its a string.
var selectedGiftnameValue = +selectedOption.dataset.price;
var total = 90 + selectedGiftnameValue;
document.getElementById("total").value = total;
}
</script>

You can try a more simple approach.
Assuming you want a dollar value I added
return total.value = Number.parseFloat(price).toFixed(2);
if not replace the above line with
total.value = price;
var price;
var total = document.getElementById('total');
var gg = document.getElementById('giftname');
gg.onchange = function() {
if (gg.value == "G0001") {
price = 90 + 60;
}
else if (gg.value == "G0002") {
price = 90 + 20;
}
else if (gg.value == "G0003") {
price = 90 + 5;
}
else if (gg.value == "G0004") {
total = 90 + 10;
}
else if (gg.value == "G0005") {
price = 90 + 100;
}
else if (gg.value == "G0006") {
price = 90 + 90;
}
else {
price = 90;
}
return total.value = Number.parseFloat(price).toFixed(2);
}
<select class="normalinput" name="giftname" id="giftname" \>
<option value="None">None</option>
<option value="G0001">Big Graduation Bear +RM60.00</option>
<option value="G0002">Small Graduation Bear +RM20.00</option>
<option value="G0003">Handcraft Gift Card +RM5.00</option>
<option value="G0004">Valentine Gift Card +RM10.00</option>
<option value="G0005">Godiva Chocolate Box +RM100.00</option>
<option value="G0006">Ferrero Rocher Love Box +RM90.00</option>
</select>
<p class="total"> Total: RM <input type="number" name="total" id="total" ></p>

Related

Javascript to select dropdown option using value from text input?

I need to select a dropdown option based on what my user will enter in a text field. The text field is a number, and the dropdown puts the number in a range to calculate a total based on the price range selected.
The part of the form that deals with this is:
<input name="input_12" id="input_1_20" type="text" value="" class="medium">
<select name="input_15" id="input_1_15">
<option value="0-100 beds|10" price="">0-100 beds </option>
<option value="101-250 beds|7.5" price=" -£ 2.50">101-250 -£ 2.50</option>
<option value="251-500 beds|5" price=" -£ 5.00">251-500 -£ 5.00</option>
<option value="501+ beds|2500" price=" +£ 2,490.00">501+ beds +£ 2,490.00</option>
</select>
The javascript I am using is:
<script>
jQuery('#input_1_20').change(function() {
var selectObj = document.getElementById('input_1_15');
var bedNumber = document.getElementById('input_1_20') ;
if (bedNumber <= '100') {
setSelectedValue(selectObj, "0-100 beds|10"); }
else if (bedNumber <= '250') {
setSelectedValue(selectObj, "101-250 beds|7.5"); }
else if (bedNumber <= '500') {
setSelectedValue(selectObj, "251-500 beds|5"); }
function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
if (selectObj.options[i].text== valueToSet) {
selectObj.options[i].selected = true;
return;
}
}
}
})
</script>
I'm not getting any javascript errors, but the select field is not being updated. Can anyone advise?
Update: Link to Fiddle - https://jsfiddle.net/xg6ktr1a/
Thanks!
Instead of looping through the select options, try simply setting the value of the select element itself. Here's a comparison of select-value-setting methods from another SO user.
Also, you're trying to use lesser-than/greater-than comparisons on strings, not numbers... so those conditions will never be met. You can fix this by coercing bedNumber to an integer, then checking that number.
jQuery('#input_1_20').change(function() {
var selectObj = document.getElementById('input_1_15');
var bedNumberInput = document.getElementById('input_1_20');
// coerce this value to a Number
var bedNumber = parseInt(bedNumberInput.value);
if (bedNumber <= 100) {
selectObj.value = "0-100 beds|10";
}
else if (bedNumber <= 250) {
selectObj.value = "101-250 beds|7.5";
}
else if (bedNumber <= 500) {
selectObj.value = "251-500 beds|5";
}
else {
selectObj.value = "501+ beds|2500";
}
});
$('#input_1_20').change(function() {
var bedNumber = parseInt(document.getElementById('input_1_20').value);
console.log(bedNumber)
if (bedNumber <= 100) {
$("#input_1_15 option[value='0-100 beds|10']").prop('selected', true);
} else if (bedNumber > 100 && bedNumber <= 250) {
$("#input_1_15 option[value='101-250 beds|7.5']").prop('selected', true);
} else if (bedNumber > 250 && bedNumber <= 500) {
$("#input_1_15 option[value='251-500 beds|5']").prop('selected', true);
} else {
$("#input_1_15 option[value='501+ beds|2500']").prop('selected', true);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input name="input_12" id="input_1_20" type="text" value="" class="medium">
<select name="input_15" id="input_1_15">
<option value="0-100 beds|10" price="">0-100 beds </option>
<option value="101-250 beds|7.5" price=" -£ 2.50">101-250 -£ 2.50</option>
<option value="251-500 beds|5" price=" -£ 5.00">251-500 -£ 5.00</option>
<option value="501+ beds|2500" price=" +£ 2,490.00">501+ beds +£ 2,490.00</option>
</select>
</form>

Issue with event listener and value not updating

I am having an issue with an event listener on a select and a value not updating but cannot figure out what the issue.
Code is below. Basically need the price field to update based on the function above it. Unfortunately i cannot have them all in the same function and need to have them separate. The first console.log does show the value for y but the second does not show the value for price.
var factors = function factor(j) {
var mySelect = document.getElementById("mySelect").value;
if (mySelect == "car") {
lease = "166";
} else if (mySelect == "truck") {
lease = "200";
}
console.log("this is my lease value - " + lease);
return lease * j;
};
var monthlyprice = function monthlyprice() {
var price = factors(1);
console.log("this is my price -" + price);
};
var type = document.getElementById("mySelect");
type.addEventListener("click", factors);
<form action="">
<label for="mySelect">Shipment Type</label>
<select id="mySelect">
<option value="car">Car</option>
<option value="truck">Truck</option>
</select>
</form>
since monthlyprice calls factor() you want to place the listener on monthlyprice
var type = document.getElementById("mySelect");
type.addEventListener("change", monthlyprice);
function monthlyprice() {
var price = factor(1)
console.log("this is my price =" + price);
};
function factor(j) {
var y;
var z = document.getElementById("mySelect").value;
if (z == "car") {
y = "166";
} else if (z == "truck") {
y = "200";
}
console.log("this is my y value - " + y);
return y * j;
};
<form action="">
<label id="label">Shipment Type</label>
<select id="mySelect">
<option value="car">Car</option>
<option value="truck">Truck</option>
</select>
</form>

calculation using dropdown box and textbox

Before you guys shoot me down for not trying the code, I am very new to Javascript and I need to implement this function into a very important work.
I got the basis dropdown calculation from this thread, Javascript drop-down form math calculation. I modified the code referred from the thread for my codes
Forgive me if my codes is totally wrong, I am still trying to do piece by piece. Will be grateful if you all can help me pinpoint the errors and/or issues.
So back to topic, I want to get the cost for each items, and then count the total cost to be calculated. The JSFiddle link is here. Appreciate for your helps rendered.
HTML CODES
<form name="priceCalc" action="">Laundry (Gentlemen)
<br/>Apparels:
<select name="gapparell" onchange="gentlemanl();">
<option value="5.00">Tie</option>
<option value="7.50">Shirt</option>
<option value="12.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="gqtyl" onchange="gentlemanl();" />
<br>
<br/>Dry Cleaning (Gentlemen)
<br/>Apparels:
<select name="gappareld" onchange="gentlemand();">
<option value="6.00">Tie</option>
<option value="8.50">Shirt</option>
<option value="13.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="gqtyd" onchange="gentlemand();" />
<br/><br/><br/>Laundry (Ladies)
<br/>Apparels:
<select name="lapparell" onchange="ladiesl();">
<option value="5.00">Tie</option>
<option value="7.50">Shirt</option>
<option value="12.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="lqtyl" onchange="ladiesl();" />
<br>
<br/>Dry Cleaning (Ladies)
<br/>Apparels:
<select name="lappareld" onchange="ladiesd();">
<option value="6.00">Tie</option>
<option value="8.50">Shirt</option>
<option value="13.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="lqtyd" onchange="ladiesd();" />
<br>Total Cost:
<input type="text" id="prices">
<br/>
<input type="button" value="Figure out pricing!" onclick="total();">
<br>
JAVASCRIPT CODES
function gentlemanl() {
var Amt = document.priceCalc.gapparell;
var Qty = document.priceCalc.gqtyl;
var price = parseInt(Qty.value) * parseFloat(Amt.value);
document.getElementById("prices").value = price;
}
function gentlemand() {
var Amt = document.priceCalc.gappareld;
var Qty = document.priceCalc.gqtyd;
var price = parseInt(Qty.value) * parseFloat(Amt.value);
document.getElementById("prices").value = price;
}
function ladiesl() {
var Amt = document.priceCalc.lapparell;
var Qty = document.priceCalc.lqtyl;
var price = parseInt(Qty.value) * parseFloat(Amt.value);
document.getElementById("prices").value = price;
}
function ladiesd() {
var Amt = document.priceCalc.lappareld;
var Qty = document.priceCalc.lqtyd;
var price = parseInt(Qty.value) * parseFloat(Amt.value);
document.getElementById("prices").value = price;
}
function total() {
//I am not sure how the function works
}
this is a working exemple of what i think you want to do : http://jsfiddle.net/gd12k4mt/5/
function gentleman1() {
var Amt = document.priceCalc.gapparell;
var Qty = document.priceCalc.gqtyl;
return parseInt(Qty.value) * parseFloat(Amt.value);
}
I designed the functions like that. With a return statement for the value of each product * the quantity.
function total() {
if(isNaN(gentleman1())) {
gentleman_laundry = 0;
} else {
gentleman_laundry = gentleman1();
}
if(isNaN(gentlemand())) {
gentleman_dry = 0;
} else {
gentleman_dry = gentlemand();
}
if(isNaN(ladies1())) {
ladies_laundry = 0;
} else {
ladies_laundry = ladies1();
}
if(isNaN(ladiesd())){
ladies_dry = 0;
} else {
ladies_dry = ladiesd();
}
var totalPrice = gentleman_laundry+gentleman_dry+ladies_laundry+ladies_dry;
document.getElementById('prices').value = totalPrice;
}
The total function is like that with a test on empty fields. In this purpose I created the variables :
var gentleman_laundry,
gentlemend_dry,
ladies_laundry,
ladies_dry;
Be sure that your functions's name is good : here you have two different names in you're html events and in your script.
I personally did without theses html listeners because we want the total price at the end I guess. So I declared only one listener on the final button.
document.getElementById('submit_button').addEventListener('click', function(){
total();
})
Hope this helped.
You can try like this,
HTML
<form name="priceCalc" action="">Laundry (Gentlemen)
<br/>Apparels:
<select id="gapparell" />
<option value="5.00">Tie</option>
<option value="7.50">Shirt</option>
<option value="12.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="gqtyl" />
<br>
<br/>Dry Cleaning (Gentlemen)
<br/>Apparels:
<select id="gappareld">
<option value="6.00">Tie</option>
<option value="8.50">Shirt</option>
<option value="13.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="gqtyd" />
<br/>
<br/>
<br/>Laundry (Ladies)
<br/>Apparels:
<select id="lapparell" >
<option value="5.00">Tie</option>
<option value="7.50">Shirt</option>
<option value="12.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="lqtyl"/>
<br>
<br/>Dry Cleaning (Ladies)
<br/>Apparels:
<select id="lappareld" onchange="ladiesd();">
<option value="6.00">Tie</option>
<option value="8.50">Shirt</option>
<option value="13.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="lqtyd" onchange="ladiesd();" />
<br>Total Cost:
<input type="text" id="prices">
<br/>
<input type="button" value="Figure out pricing!" onclick="total()">
<br>
</form>
This is JS,
function gentleman1() {
var price=0;
var e = document.getElementById('gapparell')
var Amt = e.options[e.selectedIndex].value;
var Qty = document.getElementById('gqtyl').value;
price = parseInt(Qty) * parseFloat(Amt);
return (isNaN(price)) ? 0 : price;
//document.getElementById("prices").value = price;
}
function gentlemand() {
var price=0;
var e = document.getElementById('gappareld')
var Amt = e.options[e.selectedIndex].value;
var Qty = document.getElementById('gqtyd').value;
price = parseInt(Qty) * parseFloat(Amt);
return (isNaN(price)) ? 0 : price;
}
function ladies1() {
var price=0;
var e = document.getElementById('lapparell')
var Amt = e.options[e.selectedIndex].value;
var Qty = document.getElementById('lqtyl').value;
price = parseInt(Qty) * parseFloat(Amt);
return (isNaN(price)) ? 0 : price;
}
function ladiesd() {
var price=0;
var e = document.getElementById('lappareld')
var Amt = e.options[e.selectedIndex].value;
var Qty = document.getElementById('lqtyd').value;
price = parseInt(Qty) * parseFloat(Amt);
return (isNaN(price)) ? 0 : price;
}
function total() {
var price=gentleman1()+gentlemand()+ladiesd()+ladiesd();
document.getElementById('prices').value=price;
}
Working Demo

Using Math.ceil twice - still have decimals and getting unexpected answers

I'm trying to get an input to round up at two different times in an equation but I keep ending up with decimals. Ideally the equation should take 'footage', multiply it by 12, round up to the nearest whole number, multiply by 3.5, multiply by 1.05%, round up again to the nearest whole number, and put it as the value for 'total' which is used for the value of 'picketQuantity'. Unfortunately I keep getting decimals and answers no where close to what I was expecting. For example if you enter '100' into 'footage', '6ft' into 'fenceHeight' and '1x3.5x6' ideally 'total', and therefore 'picketQuantity', should return 361 but I'm getting 447.3.
If anyone can point out where I went wrong it'd be greatly appreciated. Thanks y'all!
Here is a JSFiddle - http://jsfiddle.net/gv0029/xw3DA/
HTML:
<form>
<fieldset id="fence">
<div name="inputFence" class="inputFence">
<legend><strong>Fence Description</strong>
</legend>
<label>Footage:
<input name="footage_1" class="footage" />
</label>
<select name="fenceHeight_1" class="fenceHeight">
<option value="select">Select Fence Height</option>
<option value="6" id="fH6">6 Ft.</option>
<option value="8" id="fH8">8 Ft.</option>
</select>
<select name="fenceStyle_1" class="fenceStyle">
<option value="select">Style</option>
<option value="bnb" id="bnb">Board on Board</option>
<option value="sbs" id="sbs">Side By Side</option>
</select>
<select name="picketSize_1" class="picketSize">
<option value="select">Picket Size</option>
<option value="1x3.5x6" id="1x4">1 x 3.5 x 6</option>
<option value="1x4x6" id="1x4">1 x 4 x 6</option>
<option value="1x5x6" id="1x4">1 x 5 x 6</option>
<option value="1x5.5x6" id="1x4">1 x 5.5 x 6</option>
<option value="1x6x6" id="1x4">1 x 6 x 6</option>
</select>
<legend><strong>Post Type</strong>
</legend>
<label>Picket Quantity
<input name="picketQuantity_1" class="picketQuantity" />
</label>
</div>
</fieldset>
</form>
JS:
//Quantity for Pickets
$(document.body).on('keypress keydown keyup change', '[class^="footage"],[class^="fenceHeight"], [class^="picketSize"],[class^="fenceStyle"], [class^="picketQuantity"]', function() {
var parts = $(this).attr('name').split("_");
fenceNumber = parts[1],
footage = parseFloat($(":input[name='footage_" + fenceNumber + "'" + ']').val(), 10),
fenceHeight = $(":input[name='fenceHeight_" + fenceNumber + "'" + ']').find('option:selected').val(),
fenceStyle = $(":input[name='fenceStyle_" + fenceNumber + "'" + ']').find('option:selected').val(),
picketSize = $(":input[name='picketSize_" + fenceNumber + "'" + ']').find('option:selected').val(),
picketQuantity = $(":input[name='picketQuantity_" + fenceNumber + "'" + ']'),
total = '';
if (!isNaN(Number(fenceHeight))) {
if(fenceHeight == '6') {
if (fenceStyle == 'sbs') {
if (picketSize == '1x3.5x6' || picketSize == "1x4x6" || picketSize == "1x5x6") {
total = Math.ceil((Math.ceil((footage * 12) / 3.5))*1.05);
} else if (picketSize == '1x5.5x6' || picketSize == "1x6x6") {
total = Math.ceil((Math.ceil((footage * 12) / 5.5)) * 1.05);
} else {
total = "Select Picket Size";
}
picketQuantity.val(total);
} else if (fenceStyle == 'bnb') {
if (picketSize == '1x3.5x6' || picketSize == "1x4x6" || picketSize == "1x5x6") {
total = ((Math.ceil((footage * 12) / 8.5) * 3) * 1.05);
} else if (picketSize == '1x5.5x6' || picketSize == "1x6x6") {
total = ((Math.ceil((footage * 12) / 10.5) * 3) * 1.05);
} else {
total = "Select Picket Size";
}
picketQuantity.val(total);
} else {
picketQuantity.val("Select Fence Style");
}
} else if (fenceHeight == '8') {
total = (Math.ceil(footage / 8))*3;
picketQuantity.val(total);
}
} else {
picketQuantity.val("Select Fence Height");
}
});
At the second fenceStyle case (when fenceStyle equals bnb) there is no second Math.ceil functions in equations.
Updated fiddle: http://jsfiddle.net/xw3DA/1/.
You are multipling the whole thing with 1.05. Watch out for the braces.
For example, instead of
((Math.ceil((footage * 12) / 8.5) * 3) * 1.05);
you can do something like this:
Math.ceil((Math.ceil((footage * 12) / 8.5) * 3) * 1.05);
But I don't know if it's the correct equation for your problem.

jquery checkbox nested with select

I have checkboxes nested with select to change a span value but my problem is when I have two or more selects... I'm not good on javascript =/
How to get the problem: select value 2 on first select after select 2 in second select, and select 0 on second and 0 on first when you do it total has to be 0 but I don't know, how to do it =/
<div id="test_div">
<input class="test_class" type="checkbox" value="3,00"/>3,00
<input class="test_class" type="checkbox" value="5,00"/>5,00
<input class="test_class" type="checkbox" value="10,00"/>10,00
<input class="test_class" type="checkbox" value="15,00"/>15,00
<select class="test_class">
<option value="10,00">0</option>
<option value="10,00">1</option>
<option value="10,00">2</option>
</select>
<select class="test_class">
<option value="10,00">0</option>
<option value="10,00">1</option>
<option value="10,00">2</option>
</select>
<select class="test_class">
<option value="10,00">0</option>
<option value="10,00">1</option>
<option value="10,00">2</option>
</select>
<span id="total">0,00</span><br/>
</div>
JS:
$(function()
{
var last = 0;
$('body').on('change','.test_class', function()
{
var vt = parseFloat($('#total').html().replace(',','.'));
if($(this).is('input:checked'))
{
var val = parseFloat($(this).val().replace(',','.'));
total = val + vt;
}else if($(this).is('input'))
{
var val = parseFloat($(this).val().replace(',','.'));
total = vt - val;
}
if($(this).is('select'))
{
var val = parseFloat($(this).val().replace(',','.'));
var index = $(this).prop('selectedIndex');
if(index == 0)
{
if(last > 0)
{
total = vt - val*last;
}
last = 0;
}
if(index == 1)
{
if(last == 2)
{
total = vt - val;
}else
{
total = vt + val*index;
}
last = 1;
}
if(index == 2)
{
if(last == 1)
{
total = vt + val;
}else
{
total = vt + val*index;
}
last = 2;
}
}
total = total.toFixed(2).replace('.',',');
$('#total').html('').html(total);
});
});
Example in: http://jsfiddle.net/jvtcc/8/
$("select .test_class").change(function() {
var total;
total = 0;
$("select .test_class").each(function() {
total += parseInt($(this).value);
});
$("#total").text(total + ".00");
});

Categories